Skip to main content

glrmask\runtime\mask/
mod.rs

1pub(crate) mod profile;
2pub(crate) mod queue;
3mod static_dwa_walk;
4use static_dwa_walk::{StackWalkEvent, walk_single_stack};
5
6use crate::automata::lexer::Lexer;
7use crate::compiler::glr::accumulator::TerminalsDisallowed;
8use crate::grammar::flat::TerminalID;
9use crate::compiler::glr::labels::{DEFAULT_LABEL, encode_positive_label};
10use crate::compiler::glr::parser::{
11    lookahead_reduction_factor,
12    lookahead_reduction_factor_row_subset,
13    ParserGSS,
14};
15use crate::ds::bitset::BitSet;
16use crate::ds::leveled_gss::{
17    IndexedLeveledGss, IndexedLeveledGssNode, IndexedLowerIdentity, LeveledGSS, Merge,
18};
19use crate::ds::weight::Weight;
20use crate::runtime::artifact::IndexedDagDenseMask;
21use crate::runtime::constraint::{
22    Constraint, DenseToBufProfileStats, RuntimeTokenSetRef, RuntimeWeightRef,
23};
24use crate::runtime::state::{
25    ConstraintState, ParserStateMap, StateMaskCache, mask_scratch,
26};
27#[cfg(test)]
28use crate::runtime::state::CommitBuffers;
29use range_set_blaze::RangeSetBlaze;
30use rustc_hash::{FxHashMap, FxHashSet};
31use smallvec::SmallVec;
32use std::sync::{Arc, OnceLock};
33use std::time::Instant;
34
35use self::profile::{
36    elapsed_ns,
37    emit_mask_fast_conversion_profile_line,
38    emit_mask_inner_profile_line,
39    emit_mask_queue_debug_line,
40    initialize_runtime_config as initialize_mask_profile_config,
41    mask_delta_profile_enabled,
42    mask_fast_conversion_profile_enabled,
43    mask_inner_profile_enabled,
44    mask_queue_debug_enabled,
45    mask_single_path_to_stacks_fallback_disabled,
46    MaskProfile,
47    MaskInnerProfileStats,
48};
49use self::queue::{mask_queue_mode, MaskQueue};
50
51type DenseTokenMaskCache = FxHashMap<usize, Arc<[u64]>>;
52type DenseMaskGSS = LeveledGSS<u32, DenseMaskAcc>;
53
54/// Mask-local exact byte-transition reuse for recursive composition. Full
55/// structural equality includes scoped lexer keys, parser stacks, and delayed
56/// exclusions. Hashes only select buckets; they never prove equivalence.
57/// Once the state budget is exhausted, new frontiers keep using the original
58/// exact radix-edge evaluator. There is no compilation or persistent-cache cost.
59#[cfg(test)]
60struct RecursiveMaskTransitions {
61    states: Vec<ParserStateMap>,
62    rows: Vec<[u32; 256]>,
63    buckets: FxHashMap<u64, SmallVec<[u32; 2]>>,
64    max_states: usize,
65    byte_representatives: [u8; 256],
66}
67
68#[cfg(test)]
69#[derive(Clone)]
70enum RecursiveMaskFrontier {
71    Cached(u32),
72    Uncached(ParserStateMap),
73}
74
75/// An exact alphabet congruence over every intact leaf lexer. Equal columns
76/// reach identical states (and hence identical matches/futures) from *all*
77/// lexer states, including resets and exclusion continuations. Thus zero-width
78/// CALL/RETURN and ignored-terminal routes also cannot distinguish the bytes.
79/// Bound the proof work; large, epsilon, or virtual lexers simply keep the
80/// identity alphabet. This is mask-local work, not constraint compilation.
81#[cfg(test)]
82fn recursive_mask_byte_representatives(constraint: &Constraint) -> [u8; 256] {
83    let identity = std::array::from_fn(|byte| byte as u8);
84    let Ok(Some(layout)) = constraint.recursive_parser_layout() else { return identity; };
85    const MAX_LEXER_STATES: usize = 256;
86    if layout.leaves.is_empty() || layout.total_tokenizer_states as usize > MAX_LEXER_STATES {
87        return identity;
88    }
89    let mut leaves = Vec::with_capacity(layout.leaves.len());
90    let mut state_count = 0usize;
91    for index in 0..layout.leaves.len() {
92        let Some(leaf) = constraint.recursive_leaf_constraint(index) else { return identity; };
93        if leaf.tokenizer.has_any_virtual_runtime() || leaf.tokenizer_has_epsilon_transitions {
94            return identity;
95        }
96        state_count += leaf.tokenizer.num_states() as usize;
97        if state_count > MAX_LEXER_STATES { return identity; }
98        leaves.push(leaf);
99    }
100    let mut rows = Vec::with_capacity(state_count);
101    for leaf in leaves {
102        for state in 0..leaf.tokenizer.num_states() {
103            rows.push(std::array::from_fn::<u32, 256, _>(|byte|
104                leaf.tokenizer_fast_transitions.transition(&leaf.tokenizer, state, byte as u8)));
105        }
106    }
107    use std::hash::{Hash, Hasher};
108    let mut buckets = FxHashMap::<u64, SmallVec<[u8; 2]>>::default();
109    let mut result = identity;
110    for byte in 0..256 {
111        let mut hash = rustc_hash::FxHasher::default();
112        for row in &rows { row[byte].hash(&mut hash); }
113        let bucket = buckets.entry(hash.finish()).or_default();
114        // Compare complete columns after hashing: collisions cannot merge
115        // inequivalent bytes. One matrix allocation avoids 256 column Vecs.
116        if let Some(&representative) = bucket.iter().find(|&&representative|
117            rows.iter().all(|row| row[byte] == row[representative as usize]))
118        {
119            result[byte] = representative;
120        } else {
121            bucket.push(byte as u8);
122        }
123    }
124    result
125}
126
127#[cfg(test)]
128impl RecursiveMaskTransitions {
129    const UNKNOWN: u32 = u32::MAX;
130    const DEAD: u32 = u32::MAX - 1;
131
132    fn new(max_states: usize, byte_representatives: [u8; 256]) -> Self {
133        Self {
134            states: Vec::new(), rows: Vec::new(), buckets: FxHashMap::default(),
135            max_states, byte_representatives,
136        }
137    }
138
139    fn intern(&mut self, state: &ParserStateMap) -> Option<u32> {
140        use std::hash::{Hash, Hasher};
141        let mut hash = rustc_hash::FxHasher::default();
142        for (lexer, gss) in &state.entries {
143            lexer.hash(&mut hash);
144            gss.max_depth().hash(&mut hash);
145        }
146        let hash = hash.finish();
147        if let Some(ids) = self.buckets.get(&hash) {
148            for &id in ids {
149                if self.states[id as usize] == *state {
150                    return Some(id);
151                }
152            }
153        }
154        if self.states.len() >= self.max_states {
155            return None;
156        }
157        let id = self.states.len() as u32;
158        self.states.push(state.clone());
159        self.rows.push([Self::UNKNOWN; 256]);
160        self.buckets.entry(hash).or_default().push(id);
161        Some(id)
162    }
163
164    fn advance(
165        &mut self,
166        constraint: &Constraint,
167        parent: &RecursiveMaskFrontier,
168        buffers: &mut CommitBuffers,
169        bytes: &[u8],
170    ) -> Option<RecursiveMaskFrontier> {
171        let mut id = match parent {
172            RecursiveMaskFrontier::Cached(id) => *id,
173            RecursiveMaskFrontier::Uncached(state) => {
174                return crate::runtime::commit::advance_bytes_from_state_exact(
175                    constraint, state, buffers, bytes,
176                ).map(RecursiveMaskFrontier::Uncached);
177            }
178        };
179        for (offset, &byte) in bytes.iter().enumerate() {
180            let column = self.byte_representatives[byte as usize] as usize;
181            let cached = self.rows[id as usize][column];
182            if cached == Self::DEAD {
183                return None;
184            }
185            if cached != Self::UNKNOWN {
186                id = cached;
187                continue;
188            }
189            let next = crate::runtime::commit::advance_bytes_from_state_exact(
190                constraint, &self.states[id as usize], buffers, std::slice::from_ref(&byte),
191            );
192            let Some(next) = next else {
193                self.rows[id as usize][column] = Self::DEAD;
194                return None;
195            };
196            let Some(next_id) = self.intern(&next) else {
197                // Budget exhaustion changes only caching, not admission or
198                // traversal coverage. Finish this edge exactly, without a
199                // second vocabulary walk or loss of any live alternative.
200                return crate::runtime::commit::advance_bytes_from_state_exact(
201                    constraint, &next, buffers, &bytes[offset + 1..],
202                ).map(RecursiveMaskFrontier::Uncached);
203            };
204            self.rows[id as usize][column] = next_id;
205            id = next_id;
206        }
207        Some(RecursiveMaskFrontier::Cached(id))
208    }
209}
210
211const DELTA_SEED_MIN_SAVINGS: u64 = 2048;
212const MASK_SINGLE_PATH_DIRECT_MAX_DEPTH: u32 = 64;
213const MASK_SINGLE_PATH_DIRECT_INLINE_PATH_CAPACITY: usize = 64;
214const MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_PATHS: usize = 128;
215// Many independent lexer states with one parser stack are cheap to replay.
216// Expanding many alternatives of ONE GSS is different: it duplicates shared
217// parser suffixes and dense mask operations. Keep small local ambiguity direct,
218// but let the exact indexed-DAG evaluator retain sharing for wider GSSes.
219// This bounds speculation, not the language: an incomplete enumeration returns
220// false before touching the output, and the next evaluator visits the full GSS.
221const MASK_SINGLE_PATH_DIRECT_MAX_PATHS_PER_GSS: usize = 16;
222const MASK_SINGLE_PATH_DIRECT_INLINE_STACK_DEPTH: usize = 64;
223const MASK_SINGLE_PATH_DIRECT_MAX_PLAN_OPS: usize = 1024;
224// Below this much parser-stack work, grouping and compiling plans costs more
225// than replaying the stacks directly even when a duplicate exists.
226const MASK_SINGLE_PATH_DIRECT_MIN_PLAN_STACK_VALUES: usize = 128;
227// Count concrete stack values only after the path-count gate. Ambiguous lexer
228// frontiers commonly carry the same small parser language under several
229// tokenizer states; 1,024 still bounds the direct walk tightly while admitting
230// the bounded 33-64-path frontiers already supported by commit.
231// This keeps the exact lexer/parser relation flat instead of forcing indexed-DAG
232// construction after a successful bounded commit.
233const MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_STACK_VALUES: usize = 1024;
234const MASK_SINGLE_PATH_DIRECT_TWO_PASS_MIN_STATE_COUNT: usize =
235    MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_PATHS / 2;
236
237#[inline]
238fn set_original_mask_bit(buf: &mut [u32], token_id: u32) {
239    let word = token_id as usize / 32;
240    let bit = token_id % 32;
241    if let Some(slot) = buf.get_mut(word) {
242        *slot |= 1u32 << bit;
243    }
244}
245
246#[inline(always)]
247fn original_mask_contains(buf: &[u32], token_id: u32) -> bool {
248    buf.get(token_id as usize / 32)
249        .is_some_and(|word| word & (1u32 << (token_id % 32)) != 0)
250}
251
252/// Test-only switch for the segmented-mask stage trace. Enabled by
253/// `GLRMASK_DEBUG_MASK_STAGES`; compiled only under `cfg(test)`.
254#[cfg(test)]
255fn segmented_mask_stage_trace_enabled() -> bool {
256    crate::env::var_os("GLRMASK_DEBUG_MASK_STAGES").is_some()
257}
258
259#[cfg(test)]
260fn segmented_mask_bits(buf: &[u32]) -> Vec<u32> {
261    let mut bits = Vec::new();
262    for (word_index, &word) in buf.iter().enumerate() {
263        let mut word = word;
264        while word != 0 {
265            let bit = word.trailing_zeros() as usize;
266            bits.push((word_index * 32 + bit) as u32);
267            word &= word - 1;
268        }
269    }
270    bits
271}
272
273#[cfg(test)]
274fn segmented_mask_stage_trace(stage: &str, buf: &[u32]) {
275    if !segmented_mask_stage_trace_enabled() {
276        return;
277    }
278    let bits = segmented_mask_bits(buf);
279    eprintln!(
280        "[mask-stages] {stage} token8={} token9={} bits={bits:?}",
281        bits.contains(&8),
282        bits.contains(&9),
283    );
284}
285
286
287fn exact_component_trigger_accepted_weight(
288    constraint: &Constraint,
289    dwa: &crate::automata::weighted_u32::dwa::DWA,
290    top_first: &[u32],
291) -> Weight {
292    let mut ops = crate::ds::weight::ScopedWeightOpCache::default();
293    let mut state_id = dwa.start_state();
294    let mut path_weight = Weight::all();
295    let mut accepted = Weight::empty();
296    let accumulate = |state_id: u32,
297                      path_weight: &Weight,
298                      accepted: &mut Weight,
299                      ops: &mut crate::ds::weight::ScopedWeightOpCache| {
300        if let Some(final_weight) = dwa
301            .states()
302            .get(state_id as usize)
303            .and_then(|state| state.final_weight.as_ref())
304        {
305            let contribution = ops.intersection(path_weight, final_weight);
306            if !contribution.is_empty() {
307                *accepted = ops.union(accepted, &contribution);
308            }
309        }
310    };
311    accumulate(state_id, &path_weight, &mut accepted, &mut ops);
312    for &parser_state in top_first {
313        let Some(state) = dwa.states().get(state_id as usize) else {
314            break;
315        };
316        let positive = encode_positive_label(parser_state);
317        let transition = state
318            .transitions
319            .get(&positive)
320            .or_else(|| {
321                constraint
322                    .parser_state_domain_label(parser_state)
323                    .and_then(|label| state.transitions.get(&label))
324            })
325            .or_else(|| state.transitions.get(&DEFAULT_LABEL));
326        let Some((target, edge_weight)) = transition else {
327            break;
328        };
329        path_weight = ops.intersection(&path_weight, edge_weight);
330        if path_weight.is_empty() {
331            break;
332        }
333        state_id = *target;
334        accumulate(state_id, &path_weight, &mut accepted, &mut ops);
335    }
336    accepted
337}
338
339fn single_path_direct_stack_work(
340    stack_lengths: impl IntoIterator<Item = usize>,
341) -> Option<usize> {
342    let mut total = 0usize;
343    for len in stack_lengths {
344        total = total.saturating_add(len);
345        if total > MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_STACK_VALUES {
346            return None;
347        }
348    }
349    Some(total)
350}
351
352#[inline]
353fn single_path_direct_plan_reuse_dominates(
354    path_count: usize,
355    total_stack_values: usize,
356    repeated_stack_values: usize,
357) -> bool {
358    path_count >= 3
359        && total_stack_values >= MASK_SINGLE_PATH_DIRECT_MIN_PLAN_STACK_VALUES
360        && repeated_stack_values
361            > total_stack_values.saturating_sub(repeated_stack_values)
362}
363
364#[derive(Clone, Copy)]
365enum SinglePathDirectPlanOp<'a> {
366    Merge(RuntimeWeightRef<'a>),
367    Intersect(RuntimeWeightRef<'a>),
368}
369
370#[derive(Clone, Copy)]
371struct SinglePathDirectStackPlan {
372    representative_path: usize,
373    stack_fingerprint: u64,
374    ops_start: usize,
375    ops_end: usize,
376}
377
378#[inline]
379fn single_path_direct_stack_fingerprint(stack: &[u32]) -> u64 {
380    // FNV-1a is sufficient here: equality is still checked before sharing a
381    // plan, so the fingerprint only avoids repeatedly comparing long stacks.
382    let mut fingerprint = 0xcbf29ce484222325u64;
383    for &state in stack {
384        fingerprint ^= u64::from(state);
385        fingerprint = fingerprint.wrapping_mul(0x100000001b3);
386    }
387    fingerprint ^ (stack.len() as u64).wrapping_mul(0x9e3779b97f4a7c15)
388}
389
390fn materialize_single_path_seed_intersection(
391    base: &[u64],
392    dense: &mut Vec<u64>,
393    internal_tsid: u32,
394    weight: RuntimeWeightRef<'_>,
395    constraint: &Constraint,
396) -> bool {
397    debug_assert!(!weight.is_full());
398    let Some(token_set) = weight.token_set_for_tsid(internal_tsid) else {
399        dense.clear();
400        return false;
401    };
402
403    dense.clear();
404    dense.resize(base.len(), 0);
405    if let Some(mask) = constraint.runtime_token_set_dense_mask(token_set) {
406        let mut any = false;
407        for (idx, dense_word) in dense.iter_mut().enumerate() {
408            *dense_word = base[idx] & mask.get(idx).copied().unwrap_or(0);
409            any |= *dense_word != 0;
410        }
411        return any;
412    }
413
414    let mut any = false;
415    DenseMaskAcc::for_each_runtime_token_range_word(token_set, base.len(), |word_idx, token_mask| {
416        let word = base[word_idx] & token_mask;
417        dense[word_idx] |= word;
418        any |= word != 0;
419    });
420    any
421}
422
423/// Same dense/range intersection for ordinary and boundary single-stack masks.
424/// The lookup closure specializes away when no precomputed dense row is present.
425#[inline]
426fn intersect_static_dense_with_weight<'w, 'm>(
427    dense: &mut Vec<u64>,
428    aux: &mut Vec<u64>,
429    internal_tsid: u32,
430    weight: RuntimeWeightRef<'w>,
431    dense_mask: impl FnOnce(RuntimeTokenSetRef<'w>) -> Option<&'m [u64]>,
432) -> bool {
433    if weight.is_full() {
434        return dense.iter().any(|&word| word != 0);
435    }
436
437    let Some(token_set) = weight.token_set_for_tsid(internal_tsid) else {
438        dense.fill(0);
439        return false;
440    };
441    if let Some(mask) = dense_mask(token_set) {
442        let mut any = false;
443        for (idx, dense_word) in dense.iter_mut().enumerate() {
444            *dense_word &= mask.get(idx).copied().unwrap_or(0);
445            any |= *dense_word != 0;
446        }
447        return any;
448    }
449
450    aux.clear();
451    aux.resize(dense.len(), 0);
452    DenseMaskAcc::for_each_runtime_token_range_word(token_set, dense.len(), |word_idx, token_mask| {
453        aux[word_idx] |= dense[word_idx] & token_mask;
454    });
455    std::mem::swap(dense, aux);
456    dense.iter().any(|&word| word != 0)
457}
458
459pub(crate) fn indexed_dag_mask_enabled() -> bool {
460    static ENABLED: OnceLock<bool> = OnceLock::new();
461    *ENABLED.get_or_init(|| {
462        crate::env::var("GLRMASK_ENABLE_INDEXED_DAG_MASK")
463            .map(|value| {
464                let normalized = value.trim().to_ascii_lowercase();
465                matches!(normalized.as_str(), "1" | "true" | "yes" | "on")
466            })
467            .unwrap_or(false)
468    })
469}
470
471fn indexed_dag_mask_profile_enabled() -> bool {
472    crate::env::var_os("GLRMASK_PROFILE_INDEXED_DAG_MASK").is_some()
473}
474
475fn dynamic_mask_equivalence_assert_enabled() -> bool {
476    static ENABLED: OnceLock<bool> = OnceLock::new();
477    *ENABLED.get_or_init(|| {
478        crate::env::var("GLRMASK_ASSERT_DYNAMIC_MASK_EQUIVALENCE")
479            .map(|value| {
480                let normalized = value.trim().to_ascii_lowercase();
481                matches!(normalized.as_str(), "1" | "true" | "yes" | "on")
482            })
483            .unwrap_or(false)
484    })
485}
486
487pub(crate) fn initialize_runtime_config() {
488    let _ = dynamic_mask_equivalence_assert_enabled();
489    let _ = indexed_dag_mask_enabled();
490    initialize_mask_profile_config();
491    let _ = mask_queue_mode();
492}
493
494fn assert_dynamic_mask_equivalence(state: &ConstraintState, static_mask: &[u32]) {
495    if !dynamic_mask_equivalence_assert_enabled() {
496        return;
497    }
498
499    let mut dynamic_mask = vec![0u32; state.constraint.body_mask_len()];
500    crate::compiler::boundary_transfer::permit_strict_static_dynamic(|| {
501        state.fill_mask_dynamic(&mut dynamic_mask)
502    });
503    if static_mask == dynamic_mask {
504        return;
505    }
506
507    let mut differing_token_ids = Vec::new();
508    let mut differing_count = 0usize;
509    for (word_index, (&static_word, &dynamic_word)) in
510        static_mask.iter().zip(&dynamic_mask).enumerate()
511    {
512        let mut differing_bits = static_word ^ dynamic_word;
513        while differing_bits != 0 {
514            let bit = differing_bits.trailing_zeros() as usize;
515            differing_count += 1;
516            if differing_token_ids.len() < 64 {
517                differing_token_ids.push(word_index * 32 + bit);
518            }
519            differing_bits &= differing_bits - 1;
520        }
521    }
522
523    panic!(
524        "dynamic/static mask mismatch at generation {}: differing_tokens={} first_differing_token_ids={:?} parser_state_keys={:?}",
525        state.generation(),
526        differing_count,
527        differing_token_ids,
528        state.state.keys().copied().collect::<Vec<_>>(),
529    );
530}
531
532#[derive(Clone, Copy, PartialEq, Eq, Hash)]
533enum RuntimeTokenSetKey {
534    Materialized(usize),
535    PackedDwa(u32),
536    PackedPool(u32),
537}
538
539impl RuntimeTokenSetKey {
540    #[inline]
541    fn from_ref(token_set: RuntimeTokenSetRef<'_>) -> Self {
542        if let Some(key) = token_set.materialized_key() {
543            Self::Materialized(key)
544        } else if let Some(id) = token_set.packed_id() {
545            Self::PackedDwa(id)
546        } else {
547            Self::PackedPool(
548                token_set
549                    .packed_pool_id()
550                    .expect("runtime token set has identity"),
551            )
552        }
553    }
554}
555
556#[derive(Clone, Copy, PartialEq, Eq, Hash)]
557struct DenseTokenSetIntersectionKey {
558    tsid: u32,
559    dense: usize,
560    dense_len: usize,
561    token_set: RuntimeTokenSetKey,
562}
563
564type DenseTokenSetIntersectionSmallCache =
565    SmallVec<[(Arc<[u64]>, RuntimeTokenSetKey, Option<Arc<[u64]>>); 8]>;
566
567#[derive(Clone, PartialEq, Eq, Hash)]
568struct DenseGssTransitionKey {
569    lower: usize,
570    entries: SmallVec<[(u32, usize, usize, usize); 4]>,
571}
572
573
574/// Dense bitmap accumulator used while walking the parser DWA.
575///
576/// Key:
577///   parser-DWA internal tokenizer-state id.
578///
579/// Value:
580///   dense bitmap of final shared constraint-internal token ids.
581///
582/// The token ids here must match parser-DWA Weight token ids. They also match
583/// Constraint.possible_matches bitmap token ids after compile-time vocab
584/// reconciliation.
585#[derive(Clone, PartialEq, Eq, Hash)]
586struct DenseMaskAcc(SmallVec<[(u32, Arc<[u64]>); 2]>);
587
588impl DenseMaskAcc {
589    fn from_dense(tsid: u32, dense: Vec<u64>) -> Option<Self> {
590        if dense.iter().all(|&word| word == 0) {
591            return None;
592        }
593
594        let dense: Arc<[u64]> = dense.into();
595        let mut entries = SmallVec::new();
596        entries.push((tsid, dense));
597        Some(Self(entries))
598    }
599
600    fn from_dense_arc(tsid: u32, dense: Arc<[u64]>) -> Option<Self> {
601        if dense.iter().all(|&word| word == 0) {
602            return None;
603        }
604
605        let mut entries = SmallVec::new();
606        entries.push((tsid, dense));
607        Some(Self(entries))
608    }
609
610    fn from_dense_arc_for_tsids(tsids: &[u32], dense: Arc<[u64]>) -> Option<Self> {
611        if tsids.is_empty() || dense.iter().all(|&word| word == 0) {
612            return None;
613        }
614
615        let mut entries = SmallVec::with_capacity(tsids.len());
616        for &tsid in tsids {
617            entries.push((tsid, Arc::clone(&dense)));
618        }
619        Some(Self(entries))
620    }
621
622    fn is_empty(&self) -> bool {
623        self.0.is_empty()
624    }
625
626    #[inline]
627    fn bit_range_mask(lo_bit: usize, hi_bit: usize) -> u64 {
628        debug_assert!(lo_bit <= hi_bit);
629        debug_assert!(hi_bit < 64);
630
631        let high_mask = if hi_bit == 63 {
632            !0u64
633        } else {
634            (1u64 << (hi_bit + 1)) - 1
635        };
636
637        let low_mask = if lo_bit == 0 {
638            0
639        } else {
640            (1u64 << lo_bit) - 1
641        };
642
643        high_mask & !low_mask
644    }
645
646    fn for_each_token_range_word<F>(tokens: &RangeSetBlaze<u32>, word_limit: usize, mut f: F)
647    where
648        F: FnMut(usize, u64),
649    {
650        if word_limit == 0 {
651            return;
652        }
653
654        let max_token_exclusive = word_limit.saturating_mul(64);
655        if max_token_exclusive == 0 {
656            return;
657        }
658
659        for range in tokens.ranges() {
660            let lo = *range.start() as usize;
661            if lo >= max_token_exclusive {
662                continue;
663            }
664
665            let hi = (*range.end() as usize).min(max_token_exclusive - 1);
666            if lo > hi {
667                continue;
668            }
669
670            let word_lo = lo / 64;
671            let word_hi = hi / 64;
672
673            for word_idx in word_lo..=word_hi {
674                let lo_bit = if word_idx == word_lo { lo % 64 } else { 0 };
675                let hi_bit = if word_idx == word_hi { hi % 64 } else { 63 };
676                f(word_idx, Self::bit_range_mask(lo_bit, hi_bit));
677            }
678        }
679    }
680
681    fn for_each_runtime_token_range_word<F>(
682        tokens: RuntimeTokenSetRef<'_>,
683        word_limit: usize,
684        mut f: F,
685    ) where
686        F: FnMut(usize, u64),
687    {
688        if word_limit == 0 {
689            return;
690        }
691        let max_token_exclusive = word_limit.saturating_mul(64);
692        if max_token_exclusive == 0 {
693            return;
694        }
695        tokens.for_each_range(|start, end| {
696            let lo = start as usize;
697            if lo >= max_token_exclusive {
698                return;
699            }
700            let hi = (end as usize).min(max_token_exclusive - 1);
701            if lo > hi {
702                return;
703            }
704            let word_lo = lo / 64;
705            let word_hi = hi / 64;
706            for word_idx in word_lo..=word_hi {
707                let lo_bit = if word_idx == word_lo { lo % 64 } else { 0 };
708                let hi_bit = if word_idx == word_hi { hi % 64 } else { 63 };
709                f(word_idx, Self::bit_range_mask(lo_bit, hi_bit));
710            }
711        });
712    }
713
714    fn intersect_dense_with_runtime_token_set(
715        dense: &[u64],
716        token_set: RuntimeTokenSetRef<'_>,
717        precomputed: &DenseTokenMaskCache,
718    ) -> Option<Arc<[u64]>> {
719        if let Some(key) = token_set.materialized_key()
720            && let Some(mask) = precomputed.get(&key) {
721                let mut out = vec![0u64; dense.len()];
722                let mut any = false;
723                for i in 0..dense.len() {
724                    let word = dense[i] & mask.get(i).copied().unwrap_or(0);
725                    any |= word != 0;
726                    out[i] = word;
727                }
728                return any.then(|| out.into());
729            }
730        let mut out = vec![0u64; dense.len()];
731        let mut any = false;
732        Self::for_each_runtime_token_range_word(token_set, dense.len(), |word_idx, token_mask| {
733            let word = dense[word_idx] & token_mask;
734            if word != 0 {
735                out[word_idx] |= word;
736                any = true;
737            }
738        });
739        any.then(|| out.into())
740    }
741
742    fn or_dense_and_runtime_token_set_into(
743        dense: &[u64],
744        token_set: RuntimeTokenSetRef<'_>,
745        precomputed: &DenseTokenMaskCache,
746        merged: &mut [u64],
747    ) {
748        if let Some(key) = token_set.materialized_key()
749            && let Some(mask) = precomputed.get(&key) {
750                let n = dense.len().min(mask.len()).min(merged.len());
751                for i in 0..n {
752                    merged[i] |= dense[i] & mask[i];
753                }
754                return;
755            }
756        let word_limit = dense.len().min(merged.len());
757        Self::for_each_runtime_token_range_word(token_set, word_limit, |word_idx, token_mask| {
758            merged[word_idx] |= dense[word_idx] & token_mask;
759        });
760    }
761
762    fn intersect_with_runtime_weight_reuse(
763        &self,
764        weight: RuntimeWeightRef<'_>,
765        precomputed: &DenseTokenMaskCache,
766    ) -> Option<Self> {
767        if self.is_empty() {
768            return None;
769        }
770        if weight.is_full() {
771            return Some(self.clone());
772        }
773        let mut entries = SmallVec::new();
774        for (tsid, dense) in &self.0 {
775            let Some(token_set) = weight.token_set_for_tsid(*tsid) else {
776                continue;
777            };
778            if let Some(intersection) =
779                Self::intersect_dense_with_runtime_token_set(dense, token_set, precomputed)
780            {
781                entries.push((*tsid, intersection));
782            }
783        }
784        (!entries.is_empty()).then_some(Self(entries))
785    }
786
787    fn intersect_with_runtime_weight_small_cached(
788        &self,
789        weight: RuntimeWeightRef<'_>,
790        precomputed: &DenseTokenMaskCache,
791        cache: &mut DenseTokenSetIntersectionSmallCache,
792    ) -> Option<Self> {
793        if self.is_empty() {
794            return None;
795        }
796        if weight.is_full() {
797            return Some(self.clone());
798        }
799        let mut result = SmallVec::new();
800        for (tsid, dense) in &self.0 {
801            let Some(token_set) = weight.token_set_for_tsid(*tsid) else {
802                continue;
803            };
804            let token_key = RuntimeTokenSetKey::from_ref(token_set);
805            let cached = cache.iter().find(|(cached_dense, cached_token_set, _)| {
806                Arc::ptr_eq(cached_dense, dense) && *cached_token_set == token_key
807            });
808            let intersection = if let Some((_, _, result)) = cached {
809                result.clone()
810            } else {
811                let result = Self::intersect_dense_with_runtime_token_set(
812                    dense,
813                    token_set,
814                    precomputed,
815                );
816                if cache.len() < cache.inline_size() {
817                    cache.push((Arc::clone(dense), token_key, result.clone()));
818                }
819                result
820            };
821            if let Some(intersection) = intersection {
822                result.push((*tsid, intersection));
823            }
824        }
825        (!result.is_empty()).then_some(Self(result))
826    }
827
828    fn intersect_dense_with_tokens(
829        dense: &[u64],
830        tokens: &RangeSetBlaze<u32>,
831    ) -> Option<Arc<[u64]>> {
832        if dense.is_empty() || tokens.is_empty() {
833            return None;
834        }
835
836        let mut out = vec![0u64; dense.len()];
837        let mut any = false;
838
839        Self::for_each_token_range_word(tokens, dense.len(), |word_idx, token_mask| {
840            let word = dense[word_idx] & token_mask;
841            if word != 0 {
842                out[word_idx] |= word;
843                any = true;
844            }
845        });
846
847        if any {
848            Some(out.into())
849        } else {
850            None
851        }
852    }
853
854    fn intersect_dense_with_token_set(
855        dense: &[u64],
856        token_set: &Arc<RangeSetBlaze<u32>>,
857        precomputed: &DenseTokenMaskCache,
858    ) -> Option<Arc<[u64]>> {
859        let key = Arc::as_ptr(token_set) as usize;
860
861        if let Some(mask) = precomputed.get(&key) {
862            let mut out = vec![0u64; dense.len()];
863            let mut any = false;
864
865            for i in 0..dense.len() {
866                let word = dense[i] & mask.get(i).copied().unwrap_or(0);
867                if word != 0 {
868                    any = true;
869                }
870                out[i] = word;
871            }
872
873            if any {
874                Some(out.into())
875            } else {
876                None
877            }
878        } else {
879            Self::intersect_dense_with_tokens(dense, token_set)
880        }
881    }
882
883    fn or_dense_and_token_set_into(
884        dense: &[u64],
885        token_set: &Arc<RangeSetBlaze<u32>>,
886        precomputed: &DenseTokenMaskCache,
887        merged: &mut [u64],
888    ) {
889        let key = Arc::as_ptr(token_set) as usize;
890
891        if let Some(mask) = precomputed.get(&key) {
892            let n = dense.len().min(mask.len()).min(merged.len());
893            for i in 0..n {
894                merged[i] |= dense[i] & mask[i];
895            }
896        } else {
897            let word_limit = dense.len().min(merged.len());
898            Self::for_each_token_range_word(token_set, word_limit, |word_idx, token_mask| {
899                merged[word_idx] |= dense[word_idx] & token_mask;
900            });
901        }
902    }
903
904    fn intersect_with_weight(
905        &self,
906        weight: &Weight,
907        precomputed: &DenseTokenMaskCache,
908    ) -> Option<Self> {
909        if self.is_empty() {
910            return None;
911        }
912
913        if weight.is_full() {
914            return Some(self.clone());
915        }
916
917        let mut result = SmallVec::new();
918
919        for (tsid, dense) in &self.0 {
920            let Some(token_set) = weight.token_set_for_tsid_ref(*tsid) else {
921                continue;
922            };
923
924            if let Some(intersection) =
925                Self::intersect_dense_with_token_set(dense, token_set, precomputed)
926            {
927                result.push((*tsid, intersection));
928            }
929        }
930
931        if result.is_empty() {
932            None
933        } else {
934            Some(Self(result))
935        }
936    }
937
938    fn intersect_with_weight_cached(
939        &self,
940        weight: &Weight,
941        precomputed: &DenseTokenMaskCache,
942        cache: &mut FxHashMap<DenseTokenSetIntersectionKey, Option<Arc<[u64]>>>,
943    ) -> Option<Self> {
944        if self.is_empty() {
945            return None;
946        }
947        if weight.is_full() {
948            return Some(self.clone());
949        }
950
951        let mut result = SmallVec::new();
952
953        for (tsid, dense) in &self.0 {
954            let Some(token_set) = weight.token_set_for_tsid_ref(*tsid) else {
955                continue;
956            };
957            if let Some(intersection) = Self::intersect_dense_with_token_set_cached(
958                *tsid,
959                dense,
960                token_set,
961                precomputed,
962                cache,
963            ) {
964                result.push((*tsid, intersection));
965            }
966        }
967
968        if result.is_empty() {
969            None
970        } else {
971            Some(Self(result))
972        }
973    }
974
975    fn intersect_dense_with_token_set_cached(
976        tsid: u32,
977        dense: &Arc<[u64]>,
978        token_set: &Arc<RangeSetBlaze<u32>>,
979        precomputed: &DenseTokenMaskCache,
980        cache: &mut FxHashMap<DenseTokenSetIntersectionKey, Option<Arc<[u64]>>>,
981    ) -> Option<Arc<[u64]>> {
982        let key = DenseTokenSetIntersectionKey {
983            tsid,
984            dense: dense.as_ptr() as usize,
985            dense_len: dense.len(),
986            token_set: RuntimeTokenSetKey::Materialized(Arc::as_ptr(token_set) as usize),
987        };
988        if let Some(cached) = cache.get(&key) {
989            return cached.clone();
990        }
991        if let RuntimeTokenSetKey::Materialized(token_set_key) = key.token_set
992            && let Some(mask) = precomputed.get(&token_set_key) {
993            let mut any = false;
994            let mut out: Option<Vec<u64>> = None;
995            for i in 0..dense.len() {
996                let word = dense[i] & mask.get(i).copied().unwrap_or(0);
997                any |= word != 0;
998                if let Some(out) = out.as_mut() {
999                    out.push(word);
1000                } else if word != dense[i] {
1001                    let mut new_out = Vec::with_capacity(dense.len());
1002                    new_out.extend_from_slice(&dense[..i]);
1003                    new_out.push(word);
1004                    out = Some(new_out);
1005                }
1006            }
1007            let result = if !any {
1008                None
1009            } else if let Some(out) = out {
1010                Some(out.into())
1011            } else {
1012                Some(Arc::clone(dense))
1013            };
1014            cache.insert(key, result.clone());
1015            return result;
1016            }
1017        let result = Self::intersect_dense_with_token_set(dense, token_set, precomputed);
1018        cache.insert(key, result.clone());
1019        result
1020    }
1021
1022    fn intersect_with_weight_small_cached(
1023        &self,
1024        weight: &Weight,
1025        precomputed: &DenseTokenMaskCache,
1026        cache: &mut DenseTokenSetIntersectionSmallCache,
1027    ) -> Option<Self> {
1028        if self.is_empty() {
1029            return None;
1030        }
1031        if weight.is_full() {
1032            return Some(self.clone());
1033        }
1034
1035        let mut result = SmallVec::new();
1036        for (tsid, dense) in &self.0 {
1037            let Some(token_set) = weight.token_set_for_tsid_ref(*tsid) else {
1038                continue;
1039            };
1040            if let Some(intersection) = Self::intersect_dense_with_token_set_small_cached(
1041                dense,
1042                token_set,
1043                precomputed,
1044                cache,
1045            ) {
1046                result.push((*tsid, intersection));
1047            }
1048        }
1049
1050        (!result.is_empty()).then_some(Self(result))
1051    }
1052
1053    fn intersect_dense_with_token_set_small_cached(
1054        dense: &Arc<[u64]>,
1055        token_set: &Arc<RangeSetBlaze<u32>>,
1056        precomputed: &DenseTokenMaskCache,
1057        cache: &mut DenseTokenSetIntersectionSmallCache,
1058    ) -> Option<Arc<[u64]>> {
1059        let token_set_key = RuntimeTokenSetKey::Materialized(Arc::as_ptr(token_set) as usize);
1060        if let Some((_, _, result)) = cache.iter().find(|(cached_dense, cached_token_set, _)| {
1061            Arc::ptr_eq(cached_dense, dense) && *cached_token_set == token_set_key
1062        }) {
1063            return result.clone();
1064        }
1065
1066        let result = Self::intersect_dense_with_token_set(dense, token_set, precomputed);
1067        if cache.len() < cache.inline_size() {
1068            cache.push((Arc::clone(dense), token_set_key, result.clone()));
1069        }
1070        result
1071    }
1072
1073    fn intersect_dense_with_token_set_reuse(
1074        dense: &Arc<[u64]>,
1075        token_set: &Arc<RangeSetBlaze<u32>>,
1076        precomputed: &DenseTokenMaskCache,
1077    ) -> Option<Arc<[u64]>> {
1078        let key = Arc::as_ptr(token_set) as usize;
1079        if let Some(mask) = precomputed.get(&key) {
1080            let mut any = false;
1081            let mut out: Option<Vec<u64>> = None;
1082            for index in 0..dense.len() {
1083                let word = dense[index] & mask.get(index).copied().unwrap_or(0);
1084                any |= word != 0;
1085                if let Some(out) = out.as_mut() {
1086                    out.push(word);
1087                } else if word != dense[index] {
1088                    let mut changed = Vec::with_capacity(dense.len());
1089                    changed.extend_from_slice(&dense[..index]);
1090                    changed.push(word);
1091                    out = Some(changed);
1092                }
1093            }
1094            return if !any {
1095                None
1096            } else if let Some(out) = out {
1097                Some(out.into())
1098            } else {
1099                Some(Arc::clone(dense))
1100            };
1101        }
1102
1103        let mut out = vec![0u64; dense.len()];
1104        let mut any = false;
1105        Self::for_each_token_range_word(token_set, dense.len(), |word_index, token_mask| {
1106            let word = dense[word_index] & token_mask;
1107            out[word_index] |= word;
1108            any |= word != 0;
1109        });
1110        if !any {
1111            return None;
1112        }
1113        if out.as_slice() == dense.as_ref() {
1114            Some(Arc::clone(dense))
1115        } else {
1116            Some(out.into())
1117        }
1118    }
1119
1120    fn intersect_with_weight_reuse(
1121        &self,
1122        weight: &Weight,
1123        precomputed: &DenseTokenMaskCache,
1124    ) -> Option<Self> {
1125        if self.is_empty() {
1126            return None;
1127        }
1128        if weight.is_full() {
1129            return Some(self.clone());
1130        }
1131        let mut entries = SmallVec::new();
1132        for (tsid, dense) in &self.0 {
1133            let Some(token_set) = weight.token_set_for_tsid_ref(*tsid) else {
1134                continue;
1135            };
1136            if let Some(intersection) =
1137                Self::intersect_dense_with_token_set_reuse(dense, token_set, precomputed)
1138            {
1139                entries.push((*tsid, intersection));
1140            }
1141        }
1142        (!entries.is_empty()).then_some(Self(entries))
1143    }
1144
1145    fn intersect_with_weight_in_place(
1146        &mut self,
1147        weight: &Weight,
1148        precomputed: &DenseTokenMaskCache,
1149    ) -> bool {
1150        if self.is_empty() {
1151            return false;
1152        }
1153        if weight.is_full() {
1154            return true;
1155        }
1156
1157        let mut idx = 0usize;
1158        while idx < self.0.len() {
1159            let (tsid, dense) = &mut self.0[idx];
1160            let Some(token_set) = weight.token_set_for_tsid_ref(*tsid) else {
1161                self.0.remove(idx);
1162                continue;
1163            };
1164
1165            let key = Arc::as_ptr(token_set) as usize;
1166            if let Some(mask) = precomputed.get(&key) {
1167                let dense_mut = Arc::make_mut(dense);
1168                let mut any = false;
1169                for i in 0..dense_mut.len() {
1170                    let word = dense_mut[i] & mask.get(i).copied().unwrap_or(0);
1171                    any |= word != 0;
1172                    dense_mut[i] = word;
1173                }
1174                if any {
1175                    idx += 1;
1176                } else {
1177                    self.0.remove(idx);
1178                }
1179                continue;
1180            }
1181
1182            let Some(intersection) = Self::intersect_dense_with_token_set(dense, token_set, precomputed) else {
1183                self.0.remove(idx);
1184                continue;
1185            };
1186            *dense = intersection;
1187            idx += 1;
1188        }
1189
1190        !self.0.is_empty()
1191    }
1192
1193    fn merge_in_place(&mut self, other: &Self) {
1194        if other.is_empty() {
1195            return;
1196        }
1197        if self.is_empty() {
1198            *self = other.clone();
1199            return;
1200        }
1201        for (other_tsid, other_dense) in &other.0 {
1202            match self
1203                .0
1204                .iter()
1205                .position(|(existing_tsid, _)| existing_tsid == other_tsid)
1206            {
1207                Some(index) => {
1208                    let dense = &mut self.0[index].1;
1209                    if Arc::ptr_eq(dense, other_dense) {
1210                        continue;
1211                    }
1212                    if dense.len() == other_dense.len() {
1213                        let dense = Arc::make_mut(dense);
1214                        for (word, other_word) in dense.iter_mut().zip(other_dense.iter()) {
1215                            *word |= *other_word;
1216                        }
1217                    } else {
1218                        let len = dense.len().max(other_dense.len());
1219                        let mut combined = vec![0u64; len];
1220                        for (i, word) in dense.iter().enumerate() {
1221                            combined[i] |= *word;
1222                        }
1223                        for (i, word) in other_dense.iter().enumerate() {
1224                            combined[i] |= *word;
1225                        }
1226                        *dense = combined.into();
1227                    }
1228                }
1229                None => {
1230                    let insert_at = self
1231                        .0
1232                        .iter()
1233                        .position(|(existing_tsid, _)| existing_tsid > other_tsid)
1234                        .unwrap_or(self.0.len());
1235                    self.0
1236                        .insert(insert_at, (*other_tsid, Arc::clone(other_dense)));
1237                }
1238            }
1239        }
1240    }
1241
1242    fn or_into_merged(&self, merged: &mut [u64]) {
1243        for (_, dense) in &self.0 {
1244            let n = dense.len().min(merged.len());
1245            for i in 0..n {
1246                merged[i] |= dense[i];
1247            }
1248        }
1249    }
1250
1251    fn or_intersection_into_merged(
1252        &self,
1253        final_weight: &Weight,
1254        precomputed: &DenseTokenMaskCache,
1255        merged: &mut [u64],
1256    ) {
1257        if final_weight.is_full() {
1258            self.or_into_merged(merged);
1259            return;
1260        }
1261
1262        for (tsid, dense) in &self.0 {
1263            let Some(token_set) = final_weight.token_set_for_tsid_ref(*tsid) else {
1264                continue;
1265            };
1266
1267            Self::or_dense_and_token_set_into(dense, token_set, precomputed, merged);
1268        }
1269    }
1270}
1271
1272// ---------------------------------------------------------------------------
1273// Exact cap-free GSS x deterministic boundary-DWA evaluator (static shards).
1274//
1275// Production static boundary shards evaluate a determinized parser DWA over
1276// every concrete parser stack in the current GSS. Enumerating stacks with
1277// `for_each_stack_top_first_bounded(128, ...)` and declining past the cap is
1278// unacceptable for a claimed supported static shard: callers interpret
1279// `false` as "run the exact dynamic fallback". This evaluator computes the
1280// exact same union the enumeration denotes — union over paths of
1281// (DWA acceptance(path) intersect eligibility(path)) — by dynamic programming
1282// over the indexed GSS DAG x DWA product with memoized shared tails. No
1283// path-count cap affects correctness.
1284//
1285// Denotation (top-first read, prefix finals at every readable prefix,
1286// DEFAULT-label fallback, per-path eligibility correlation):
1287// - `lower_eval(q, L)` is the union over suffixes in `[[L]]` of the DWA
1288//   acceptance read from `q`, including the final at the empty prefix and at
1289//   every consumed prefix. Memoized on `(q, L)`; a shared tail is evaluated
1290//   once per DWA state no matter how many top prefixes reach it.
1291// - `eval_upper(q, U)` groups that union by accumulator identity (the
1292//   interface/branch-empty node id whose accumulator correlates with the
1293//   path), so filtering afterwards preserves the per-path correlation
1294//   `union_p (accept(p) intersect eligible(p))` rather than the unsound
1295//   `union accept(p) intersect union eligible(p)`.
1296// - Intersection distributes over union, so stamping a shared suffix result
1297//   with each incoming edge weight is exact.
1298// - The top-stack start-component/empty-stack filter applies only to the
1299//   first label (or the empty stack); deeper recursion is filter-free.
1300#[cfg(test)]
1301type BoundaryDagGroupMap = FxHashMap<u32, Weight>;
1302
1303#[cfg(test)]
1304struct BoundaryWeightDagEvaluator<'a> {
1305    dwa: &'a crate::automata::weighted_u32::dwa::DWA,
1306    dag: &'a IndexedLeveledGss<u32, TerminalsDisallowed>,
1307    ops: crate::ds::weight::ScopedWeightOpCache,
1308    upper_memo: FxHashMap<(u32, u32), BoundaryDagGroupMap>,
1309    lower_memo: FxHashMap<(u32, u32), Weight>,
1310    groups_memo: FxHashMap<u32, FxHashSet<u32>>,
1311    nonempty_memo: FxHashMap<u32, bool>,
1312    dwa_steps: u64,
1313    weight_unions: u64,
1314    weight_intersections: u64,
1315}
1316
1317#[cfg(test)]
1318impl<'a> BoundaryWeightDagEvaluator<'a> {
1319    fn new(
1320        dwa: &'a crate::automata::weighted_u32::dwa::DWA,
1321        dag: &'a IndexedLeveledGss<u32, TerminalsDisallowed>,
1322    ) -> Self {
1323        Self {
1324            dwa,
1325            dag,
1326            ops: crate::ds::weight::ScopedWeightOpCache::default(),
1327            upper_memo: FxHashMap::default(),
1328            lower_memo: FxHashMap::default(),
1329            groups_memo: FxHashMap::default(),
1330            nonempty_memo: FxHashMap::default(),
1331            dwa_steps: 0,
1332            weight_unions: 0,
1333            weight_intersections: 0,
1334        }
1335    }
1336
1337    fn union_into(&mut self, out: &mut Weight, incoming: &Weight) {
1338        if incoming.is_empty() {
1339            return;
1340        }
1341        self.weight_unions += 1;
1342        let merged = self.ops.union(out, incoming);
1343        *out = merged;
1344    }
1345
1346    fn intersect(&mut self, a: &Weight, b: &Weight) -> Weight {
1347        self.weight_intersections += 1;
1348        self.ops.intersection(a, b)
1349    }
1350
1351    fn dwa_edge(&mut self, state: u32, parser_state: u32) -> Option<(u32, Weight)> {
1352        self.dwa_steps += 1;
1353        let st = self.dwa.states().get(state as usize)?;
1354        let (target, weight) = st
1355            .transitions
1356            .get(&encode_positive_label(parser_state))
1357            .or_else(|| st.transitions.get(&DEFAULT_LABEL))?;
1358        Some((*target, weight.clone()))
1359    }
1360
1361    fn dwa_final(&self, state: u32) -> Weight {
1362        self.dwa
1363            .states()
1364            .get(state as usize)
1365            .and_then(|st| st.final_weight.clone())
1366            .unwrap_or_else(Weight::empty)
1367    }
1368
1369    /// Structural non-emptiness of a lower node's stack language.
1370    fn lower_nonempty(&mut self, node: u32) -> bool {
1371        if let Some(&cached) = self.nonempty_memo.get(&node) {
1372            return cached;
1373        }
1374        let dag = self.dag;
1375        let result = match &dag.nodes[node as usize] {
1376            IndexedLeveledGssNode::LowerGeneral { empty, children, .. } => {
1377                *empty || children.iter().any(|(_, child)| self.lower_nonempty(*child))
1378            }
1379            // A segment denotes its fixed prefix ++ tail, so the language is
1380            // nonempty iff the tail is (degenerate empty-values segments
1381            // denote exactly the tail).
1382            IndexedLeveledGssNode::LowerSegment { next, .. } => self.lower_nonempty(*next),
1383            IndexedLeveledGssNode::UpperBranch { .. } | IndexedLeveledGssNode::Interface { .. } => {
1384                debug_assert!(false, "lower_nonempty reached upper node");
1385                false
1386            }
1387        };
1388        self.nonempty_memo.insert(node, result);
1389        result
1390    }
1391
1392    /// Accumulator-group identities with a nonempty path language below an
1393    /// upper node (DWA-independent). Groups are keyed by the
1394    /// interface/branch-empty node id carrying the correlated accumulator.
1395    fn upper_groups(&mut self, node: u32) -> FxHashSet<u32> {
1396        if let Some(cached) = self.groups_memo.get(&node) {
1397            return cached.clone();
1398        }
1399        let dag = self.dag;
1400        let result = match &dag.nodes[node as usize] {
1401            IndexedLeveledGssNode::Interface { lower, .. } => {
1402                let mut set = FxHashSet::default();
1403                if self.lower_nonempty(*lower) {
1404                    set.insert(node);
1405                }
1406                set
1407            }
1408            IndexedLeveledGssNode::UpperBranch { empty, children } => {
1409                let mut set = FxHashSet::default();
1410                if empty.is_some() {
1411                    set.insert(node);
1412                }
1413                for (_, child) in children {
1414                    set.extend(self.upper_groups(*child));
1415                }
1416                set
1417            }
1418            IndexedLeveledGssNode::LowerGeneral { .. }
1419            | IndexedLeveledGssNode::LowerSegment { .. } => {
1420                debug_assert!(false, "upper_groups reached lower node");
1421                FxHashSet::default()
1422            }
1423        };
1424        self.groups_memo.insert(node, result.clone());
1425        result
1426    }
1427
1428    /// Consume one segment's fixed values top-first, then its tail. The caller
1429    /// guarantees the tail language is nonempty. Intermediate DWA finals are
1430    /// accumulated exactly as the per-path walk would.
1431    fn step_segment(&mut self, dwa_state: u32, values: &[u32], next: u32) -> Weight {
1432        let mut out = self.dwa_final(dwa_state);
1433        let mut cumulative = Weight::all();
1434        let mut state = dwa_state;
1435        let mut live = true;
1436        for value in values.iter().rev() {
1437            let Some((target, edge_weight)) = self.dwa_edge(state, *value) else {
1438                live = false;
1439                break;
1440            };
1441            cumulative = self.intersect(&cumulative, &edge_weight);
1442            if cumulative.is_empty() {
1443                live = false;
1444                break;
1445            }
1446            state = target;
1447            let final_here = self.dwa_final(state);
1448            let stamped = self.intersect(&cumulative, &final_here);
1449            self.union_into(&mut out, &stamped);
1450        }
1451        if live {
1452            let tail = self.lower_eval(state, next);
1453            // `tail` repeats `final(state)`, already added above; union is
1454            // idempotent so stamping the whole tail stays exact.
1455            let stamped = self.intersect(&cumulative, &tail);
1456            self.union_into(&mut out, &stamped);
1457        }
1458        out
1459    }
1460
1461    fn lower_eval(&mut self, dwa_state: u32, node: u32) -> Weight {
1462        if let Some(cached) = self.lower_memo.get(&(dwa_state, node)) {
1463            return cached.clone();
1464        }
1465        let dag = self.dag;
1466        let result = match dag.nodes[node as usize].clone() {
1467            IndexedLeveledGssNode::LowerGeneral { empty: _, children, .. } => {
1468                // Empty-prefix acceptance belongs to every stack in a
1469                // nonempty language, not just the empty stack.
1470                if !self.lower_nonempty(node) {
1471                    return Weight::empty();
1472                }
1473                let mut out = self.dwa_final(dwa_state);
1474                for (value, child) in children {
1475                    let Some((target, edge_weight)) = self.dwa_edge(dwa_state, value) else {
1476                        continue;
1477                    };
1478                    let child_result = self.lower_eval(target, child);
1479                    if child_result.is_empty() {
1480                        continue;
1481                    }
1482                    let stamped = self.intersect(&edge_weight, &child_result);
1483                    self.union_into(&mut out, &stamped);
1484                }
1485                out
1486            }
1487            IndexedLeveledGssNode::LowerSegment { values, next, .. } => {
1488                if self.lower_nonempty(next) {
1489                    self.step_segment(dwa_state, &values, next)
1490                } else {
1491                    Weight::empty()
1492                }
1493            }
1494            IndexedLeveledGssNode::UpperBranch { .. } | IndexedLeveledGssNode::Interface { .. } => {
1495                debug_assert!(false, "lower_eval reached upper node");
1496                Weight::empty()
1497            }
1498        };
1499        self.lower_memo.insert((dwa_state, node), result.clone());
1500        result
1501    }
1502
1503    fn eval_upper(&mut self, dwa_state: u32, node: u32) -> BoundaryDagGroupMap {
1504        if let Some(cached) = self.upper_memo.get(&(dwa_state, node)) {
1505            return cached.clone();
1506        }
1507        let dag = self.dag;
1508        let result = match dag.nodes[node as usize].clone() {
1509            IndexedLeveledGssNode::Interface { lower, .. } => {
1510                let weight = self.lower_eval(dwa_state, lower);
1511                let mut map = BoundaryDagGroupMap::default();
1512                if !weight.is_empty() {
1513                    map.insert(node, weight);
1514                }
1515                map
1516            }
1517            IndexedLeveledGssNode::UpperBranch { children, .. } => {
1518                let mut map = BoundaryDagGroupMap::default();
1519                for (value, child) in children {
1520                    let Some((target, edge_weight)) = self.dwa_edge(dwa_state, value) else {
1521                        continue;
1522                    };
1523                    let child_map = self.eval_upper(target, child);
1524                    for (group, weight) in child_map {
1525                        if weight.is_empty() {
1526                            continue;
1527                        }
1528                        let stamped = self.intersect(&edge_weight, &weight);
1529                        match map.get_mut(&group) {
1530                            Some(existing) => self.union_into(existing, &stamped),
1531                            None => {
1532                                map.insert(group, stamped);
1533                            }
1534                        }
1535                    }
1536                }
1537                // Empty-prefix acceptance belongs to every surviving path's
1538                // group; the per-group add preserves path-specific
1539                // eligibility correlation (each path's empty-prefix
1540                // contribution is filtered by its own accumulator later).
1541                let groups = self.upper_groups(node);
1542                let final_weight = self.dwa_final(dwa_state);
1543                if !final_weight.is_empty() {
1544                    for group in groups {
1545                        match map.get_mut(&group) {
1546                            Some(existing) => self.union_into(existing, &final_weight),
1547                            None => {
1548                                map.insert(group, final_weight.clone());
1549                            }
1550                        }
1551                    }
1552                }
1553                map
1554            }
1555            IndexedLeveledGssNode::LowerGeneral { .. }
1556            | IndexedLeveledGssNode::LowerSegment { .. } => {
1557                debug_assert!(false, "eval_upper reached lower node");
1558                BoundaryDagGroupMap::default()
1559            }
1560        };
1561        self.upper_memo.insert((dwa_state, node), result.clone());
1562        result
1563    }
1564
1565    /// First-level top-filtered lower evaluation for an interface-rooted DAG:
1566    /// only the top label (or the empty stack) is filtered, deeper recursion
1567    /// is filter-free.
1568    fn lower_eval_top_filtered(
1569        &mut self,
1570        dwa_state: u32,
1571        node: u32,
1572        top_live: &dyn Fn(Option<u32>) -> bool,
1573    ) -> Weight {
1574        let dag = self.dag;
1575        match dag.nodes[node as usize].clone() {
1576            IndexedLeveledGssNode::LowerGeneral { empty, children, .. } => {
1577                // Empty-prefix acceptance belongs to every surviving stack,
1578                // not just the empty stack.
1579                let live_empty = empty && top_live(None);
1580                let live_language = live_empty
1581                    || children
1582                        .iter()
1583                        .any(|(value, child)| top_live(Some(*value)) && self.lower_nonempty(*child));
1584                let mut out = if live_language {
1585                    self.dwa_final(dwa_state)
1586                } else {
1587                    Weight::empty()
1588                };
1589                for (value, child) in children {
1590                    if !top_live(Some(value)) {
1591                        continue;
1592                    }
1593                    let Some((target, edge_weight)) = self.dwa_edge(dwa_state, value) else {
1594                        continue;
1595                    };
1596                    let child_result = self.lower_eval(target, child);
1597                    if child_result.is_empty() {
1598                        continue;
1599                    }
1600                    let stamped = self.intersect(&edge_weight, &child_result);
1601                    self.union_into(&mut out, &stamped);
1602                }
1603                out
1604            }
1605            IndexedLeveledGssNode::LowerSegment { values, next, .. } => {
1606                if values.is_empty() {
1607                    return self.lower_eval_top_filtered(dwa_state, next, top_live);
1608                }
1609                let top = *values.last().expect("nonempty segment has a top value");
1610                if !top_live(Some(top)) || !self.lower_nonempty(next) {
1611                    return Weight::empty();
1612                }
1613                // The top passed the filter; the rest is filter-free.
1614                self.step_segment(dwa_state, &values, next)
1615            }
1616            IndexedLeveledGssNode::UpperBranch { .. } | IndexedLeveledGssNode::Interface { .. } => {
1617                debug_assert!(false, "lower_eval_top_filtered reached upper node");
1618                Weight::empty()
1619            }
1620        }
1621    }
1622
1623    /// Evaluate the whole DAG from the DWA start state. `top_live` filters
1624    /// the top stack value (`None` for the empty stack): start-component
1625    /// ownership or empty-stack acceptance. Returns group-id -> accepted
1626    /// weight; the caller resolves each group id to its accumulator and
1627    /// filters eligibility per group.
1628    fn eval_root(&mut self, top_live: &dyn Fn(Option<u32>) -> bool) -> BoundaryDagGroupMap {
1629        let dag = self.dag;
1630        let start = self.dwa.start_state();
1631        let root = dag.root;
1632        match dag.nodes[root as usize].clone() {
1633            IndexedLeveledGssNode::Interface { lower, .. } => {
1634                let weight = self.lower_eval_top_filtered(start, lower, top_live);
1635                let mut map = BoundaryDagGroupMap::default();
1636                if !weight.is_empty() {
1637                    map.insert(root, weight);
1638                }
1639                map
1640            }
1641            IndexedLeveledGssNode::UpperBranch { empty, children } => {
1642                let mut map = BoundaryDagGroupMap::default();
1643                let mut live_groups = FxHashSet::default();
1644                if empty.is_some() && top_live(None) {
1645                    live_groups.insert(root);
1646                }
1647                for (value, child) in children {
1648                    if !top_live(Some(value)) {
1649                        continue;
1650                    }
1651                    // Every language group below this child survives the top
1652                    // filter, so it owns the empty-prefix acceptance even
1653                    // when its DWA extensions are all dead.
1654                    live_groups.extend(self.upper_groups(child));
1655                    let Some((target, edge_weight)) = self.dwa_edge(start, value) else {
1656                        continue;
1657                    };
1658                    let child_map = self.eval_upper(target, child);
1659                    for (group, weight) in child_map {
1660                        if weight.is_empty() {
1661                            continue;
1662                        }
1663                        let stamped = self.intersect(&edge_weight, &weight);
1664                        match map.get_mut(&group) {
1665                            Some(existing) => self.union_into(existing, &stamped),
1666                            None => {
1667                                map.insert(group, stamped);
1668                            }
1669                        }
1670                    }
1671                }
1672                let final_weight = self.dwa_final(start);
1673                if !final_weight.is_empty() {
1674                    for group in live_groups {
1675                        match map.get_mut(&group) {
1676                            Some(existing) => self.union_into(existing, &final_weight),
1677                            None => {
1678                                map.insert(group, final_weight.clone());
1679                            }
1680                        }
1681                    }
1682                }
1683                map
1684            }
1685            IndexedLeveledGssNode::LowerGeneral { .. }
1686            | IndexedLeveledGssNode::LowerSegment { .. } => {
1687                debug_assert!(false, "boundary DAG root is not an upper node");
1688                BoundaryDagGroupMap::default()
1689            }
1690        }
1691    }
1692
1693    /// Resolve a group id to the accumulator correlated with its paths.
1694    fn group_accumulator(&self, group: u32) -> Option<TerminalsDisallowed> {
1695        match &self.dag.nodes[group as usize] {
1696            IndexedLeveledGssNode::Interface { accumulator, .. } => Some(accumulator.clone()),
1697            IndexedLeveledGssNode::UpperBranch { empty, .. } => empty.clone(),
1698            IndexedLeveledGssNode::LowerGeneral { .. }
1699            | IndexedLeveledGssNode::LowerSegment { .. } => None,
1700        }
1701    }
1702}
1703
1704// ---------------------------------------------------------------------------
1705// Exact cap-free u64 evaluator for the compact boundary DWA representation.
1706//
1707// Same DAG/product structure as the Weight evaluator above, but weights are
1708// per-(weight-id, TSID) u64 token masks for one fixed TSID. Bitwise AND
1709// distributes over OR exactly as Weight intersection distributes over union,
1710// so the same memoized grouping argument applies.
1711#[cfg(test)]
1712struct BoundaryMask64DagEvaluator<'a> {
1713    dwa: &'a crate::compiler::stages::parser_dwa::SmallBoundaryDwa,
1714    tsid: u32,
1715    dag: &'a IndexedLeveledGss<u32, TerminalsDisallowed>,
1716    upper_memo: FxHashMap<(u32, u32), FxHashMap<u32, u64>>,
1717    lower_memo: FxHashMap<(u32, u32), u64>,
1718    groups_memo: FxHashMap<u32, FxHashSet<u32>>,
1719    nonempty_memo: FxHashMap<u32, bool>,
1720    dwa_steps: u64,
1721}
1722
1723#[cfg(test)]
1724impl<'a> BoundaryMask64DagEvaluator<'a> {
1725    fn new(
1726        dwa: &'a crate::compiler::stages::parser_dwa::SmallBoundaryDwa,
1727        tsid: u32,
1728        dag: &'a IndexedLeveledGss<u32, TerminalsDisallowed>,
1729    ) -> Self {
1730        Self {
1731            dwa,
1732            tsid,
1733            dag,
1734            upper_memo: FxHashMap::default(),
1735            lower_memo: FxHashMap::default(),
1736            groups_memo: FxHashMap::default(),
1737            nonempty_memo: FxHashMap::default(),
1738            dwa_steps: 0,
1739        }
1740    }
1741
1742    fn dwa_edge(&mut self, state: u32, parser_state: u32) -> Option<(u32, u64)> {
1743        self.dwa_steps += 1;
1744        let st = self.dwa.states.get(state as usize)?;
1745        let label = encode_positive_label(parser_state);
1746        let (_, target, weight) = st
1747            .transitions
1748            .iter()
1749            .find(|(edge_label, _, _)| *edge_label == label)
1750            .or_else(|| {
1751                st.transitions
1752                    .iter()
1753                    .find(|(edge_label, _, _)| *edge_label == DEFAULT_LABEL)
1754            })?;
1755        Some((*target, self.dwa.weight_mask(*weight, self.tsid)))
1756    }
1757
1758    fn dwa_final_mask(&self, state: u32, path_mask: u64) -> u64 {
1759        let Some(st) = self.dwa.states.get(state as usize) else {
1760            return 0;
1761        };
1762        if st.final_weight == 0 {
1763            return 0;
1764        }
1765        path_mask & self.dwa.weight_mask(st.final_weight, self.tsid)
1766    }
1767
1768    fn lower_nonempty(&mut self, node: u32) -> bool {
1769        if let Some(&cached) = self.nonempty_memo.get(&node) {
1770            return cached;
1771        }
1772        let dag = self.dag;
1773        let result = match &dag.nodes[node as usize] {
1774            IndexedLeveledGssNode::LowerGeneral { empty, children, .. } => {
1775                *empty || children.iter().any(|(_, child)| self.lower_nonempty(*child))
1776            }
1777            IndexedLeveledGssNode::LowerSegment { next, .. } => self.lower_nonempty(*next),
1778            IndexedLeveledGssNode::UpperBranch { .. } | IndexedLeveledGssNode::Interface { .. } => {
1779                debug_assert!(false, "lower_nonempty reached upper node");
1780                false
1781            }
1782        };
1783        self.nonempty_memo.insert(node, result);
1784        result
1785    }
1786
1787    fn upper_groups(&mut self, node: u32) -> FxHashSet<u32> {
1788        if let Some(cached) = self.groups_memo.get(&node) {
1789            return cached.clone();
1790        }
1791        let dag = self.dag;
1792        let result = match &dag.nodes[node as usize] {
1793            IndexedLeveledGssNode::Interface { lower, .. } => {
1794                let mut set = FxHashSet::default();
1795                if self.lower_nonempty(*lower) {
1796                    set.insert(node);
1797                }
1798                set
1799            }
1800            IndexedLeveledGssNode::UpperBranch { empty, children } => {
1801                let mut set = FxHashSet::default();
1802                if empty.is_some() {
1803                    set.insert(node);
1804                }
1805                for (_, child) in children {
1806                    set.extend(self.upper_groups(*child));
1807                }
1808                set
1809            }
1810            IndexedLeveledGssNode::LowerGeneral { .. }
1811            | IndexedLeveledGssNode::LowerSegment { .. } => {
1812                debug_assert!(false, "upper_groups reached lower node");
1813                FxHashSet::default()
1814            }
1815        };
1816        self.groups_memo.insert(node, result.clone());
1817        result
1818    }
1819
1820    fn step_segment(&mut self, dwa_state: u32, values: &[u32], next: u32) -> u64 {
1821        let all = self.dwa.all_token_mask();
1822        let mut out = self.dwa_final_mask(dwa_state, all);
1823        let mut cumulative = all;
1824        let mut state = dwa_state;
1825        let mut live = true;
1826        for value in values.iter().rev() {
1827            let Some((target, edge_mask)) = self.dwa_edge(state, *value) else {
1828                live = false;
1829                break;
1830            };
1831            cumulative &= edge_mask;
1832            if cumulative == 0 {
1833                live = false;
1834                break;
1835            }
1836            state = target;
1837            out |= self.dwa_final_mask(state, cumulative);
1838        }
1839        if live {
1840            out |= cumulative & self.lower_eval(state, next);
1841        }
1842        out
1843    }
1844
1845    fn lower_eval(&mut self, dwa_state: u32, node: u32) -> u64 {
1846        if let Some(&cached) = self.lower_memo.get(&(dwa_state, node)) {
1847            return cached;
1848        }
1849        let dag = self.dag;
1850        let result = match dag.nodes[node as usize].clone() {
1851            IndexedLeveledGssNode::LowerGeneral { empty: _, children, .. } => {
1852                // Empty-prefix acceptance belongs to every stack in a
1853                // nonempty language, not just the empty stack.
1854                if !self.lower_nonempty(node) {
1855                    return 0;
1856                }
1857                let all = self.dwa.all_token_mask();
1858                let mut out = self.dwa_final_mask(dwa_state, all);
1859                for (value, child) in children {
1860                    let Some((target, edge_mask)) = self.dwa_edge(dwa_state, value) else {
1861                        continue;
1862                    };
1863                    out |= edge_mask & self.lower_eval(target, child);
1864                }
1865                out
1866            }
1867            IndexedLeveledGssNode::LowerSegment { values, next, .. } => {
1868                if self.lower_nonempty(next) {
1869                    self.step_segment(dwa_state, &values, next)
1870                } else {
1871                    0
1872                }
1873            }
1874            IndexedLeveledGssNode::UpperBranch { .. } | IndexedLeveledGssNode::Interface { .. } => {
1875                debug_assert!(false, "lower_eval reached upper node");
1876                0
1877            }
1878        };
1879        self.lower_memo.insert((dwa_state, node), result);
1880        result
1881    }
1882
1883    fn eval_upper(&mut self, dwa_state: u32, node: u32) -> FxHashMap<u32, u64> {
1884        if let Some(cached) = self.upper_memo.get(&(dwa_state, node)) {
1885            return cached.clone();
1886        }
1887        let dag = self.dag;
1888        let result = match dag.nodes[node as usize].clone() {
1889            IndexedLeveledGssNode::Interface { lower, .. } => {
1890                let mask = self.lower_eval(dwa_state, lower);
1891                let mut map = FxHashMap::default();
1892                if mask != 0 {
1893                    map.insert(node, mask);
1894                }
1895                map
1896            }
1897            IndexedLeveledGssNode::UpperBranch { children, .. } => {
1898                let mut map = FxHashMap::default();
1899                for (value, child) in children {
1900                    let Some((target, edge_mask)) = self.dwa_edge(dwa_state, value) else {
1901                        continue;
1902                    };
1903                    let child_map = self.eval_upper(target, child);
1904                    for (group, mask) in child_map {
1905                        *map.entry(group).or_insert(0) |= edge_mask & mask;
1906                    }
1907                }
1908                let all = self.dwa.all_token_mask();
1909                let final_here = self.dwa_final_mask(dwa_state, all);
1910                if final_here != 0 {
1911                    for group in self.upper_groups(node) {
1912                        *map.entry(group).or_insert(0) |= final_here;
1913                    }
1914                }
1915                map
1916            }
1917            IndexedLeveledGssNode::LowerGeneral { .. }
1918            | IndexedLeveledGssNode::LowerSegment { .. } => {
1919                debug_assert!(false, "eval_upper reached lower node");
1920                FxHashMap::default()
1921            }
1922        };
1923        self.upper_memo.insert((dwa_state, node), result.clone());
1924        result
1925    }
1926
1927    fn lower_eval_top_filtered(
1928        &mut self,
1929        dwa_state: u32,
1930        node: u32,
1931        top_live: &dyn Fn(Option<u32>) -> bool,
1932    ) -> u64 {
1933        let dag = self.dag;
1934        match dag.nodes[node as usize].clone() {
1935            IndexedLeveledGssNode::LowerGeneral { empty, children, .. } => {
1936                // Empty-prefix acceptance belongs to every surviving stack,
1937                // not just the empty stack.
1938                let live_empty = empty && top_live(None);
1939                let live_language = live_empty
1940                    || children
1941                        .iter()
1942                        .any(|(value, child)| top_live(Some(*value)) && self.lower_nonempty(*child));
1943                let all = self.dwa.all_token_mask();
1944                let mut out = if live_language {
1945                    self.dwa_final_mask(dwa_state, all)
1946                } else {
1947                    0
1948                };
1949                for (value, child) in children {
1950                    if !top_live(Some(value)) {
1951                        continue;
1952                    }
1953                    let Some((target, edge_mask)) = self.dwa_edge(dwa_state, value) else {
1954                        continue;
1955                    };
1956                    out |= edge_mask & self.lower_eval(target, child);
1957                }
1958                out
1959            }
1960            IndexedLeveledGssNode::LowerSegment { values, next, .. } => {
1961                if values.is_empty() {
1962                    return self.lower_eval_top_filtered(dwa_state, next, top_live);
1963                }
1964                let top = *values.last().expect("nonempty segment has a top value");
1965                if !top_live(Some(top)) || !self.lower_nonempty(next) {
1966                    return 0;
1967                }
1968                self.step_segment(dwa_state, &values, next)
1969            }
1970            IndexedLeveledGssNode::UpperBranch { .. } | IndexedLeveledGssNode::Interface { .. } => {
1971                debug_assert!(false, "lower_eval_top_filtered reached upper node");
1972                0
1973            }
1974        }
1975    }
1976
1977    fn eval_root(&mut self, top_live: &dyn Fn(Option<u32>) -> bool) -> FxHashMap<u32, u64> {
1978        let dag = self.dag;
1979        let start = self.dwa.start_state();
1980        let root = dag.root;
1981        match dag.nodes[root as usize].clone() {
1982            IndexedLeveledGssNode::Interface { lower, .. } => {
1983                let mask = self.lower_eval_top_filtered(start, lower, top_live);
1984                let mut map = FxHashMap::default();
1985                if mask != 0 {
1986                    map.insert(root, mask);
1987                }
1988                map
1989            }
1990            IndexedLeveledGssNode::UpperBranch { empty, children } => {
1991                let mut map = FxHashMap::default();
1992                let mut live_groups = FxHashSet::default();
1993                if empty.is_some() && top_live(None) {
1994                    live_groups.insert(root);
1995                }
1996                for (value, child) in children {
1997                    if !top_live(Some(value)) {
1998                        continue;
1999                    }
2000                    live_groups.extend(self.upper_groups(child));
2001                    let Some((target, edge_mask)) = self.dwa_edge(start, value) else {
2002                        continue;
2003                    };
2004                    let child_map = self.eval_upper(target, child);
2005                    for (group, mask) in child_map {
2006                        *map.entry(group).or_insert(0) |= edge_mask & mask;
2007                    }
2008                }
2009                let all = self.dwa.all_token_mask();
2010                let final_here = self.dwa_final_mask(start, all);
2011                if final_here != 0 {
2012                    for group in live_groups {
2013                        *map.entry(group).or_insert(0) |= final_here;
2014                    }
2015                }
2016                map
2017            }
2018            IndexedLeveledGssNode::LowerGeneral { .. }
2019            | IndexedLeveledGssNode::LowerSegment { .. } => {
2020                debug_assert!(false, "boundary DAG root is not an upper node");
2021                FxHashMap::default()
2022            }
2023        }
2024    }
2025
2026    fn group_accumulator(&self, group: u32) -> Option<TerminalsDisallowed> {
2027        match &self.dag.nodes[group as usize] {
2028            IndexedLeveledGssNode::Interface { accumulator, .. } => Some(accumulator.clone()),
2029            IndexedLeveledGssNode::UpperBranch { empty, .. } => empty.clone(),
2030            IndexedLeveledGssNode::LowerGeneral { .. }
2031            | IndexedLeveledGssNode::LowerSegment { .. } => None,
2032        }
2033    }
2034}
2035
2036#[cfg(test)]
2037mod tests {
2038    use glrmask_vocab::__private::VocabExt as _;
2039    use super::{
2040        exact_component_trigger_accepted_weight, single_path_direct_plan_reuse_dominates,
2041        single_path_direct_stack_work,
2042        DenseMaskAcc,
2043        DenseTokenMaskCache,
2044        DenseTokenSetIntersectionSmallCache,
2045        MASK_SINGLE_PATH_DIRECT_INLINE_PATH_CAPACITY,
2046        MASK_SINGLE_PATH_DIRECT_MAX_PATHS_PER_GSS,
2047        MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_STACK_VALUES,
2048    };
2049    use crate::automata::lexer::Lexer;
2050    use crate::compiler::glr::accumulator::TerminalsDisallowed;
2051    use crate::compiler::glr::parser::ParserGSS;
2052    use crate::{runtime::Constraint as Constraint, Grammar, Vocab};
2053    use range_set_blaze::RangeSetBlaze;
2054    use rustc_hash::FxHashMap;
2055    use std::sync::Arc;
2056
2057    fn precomputed_for(
2058        token_set: &Arc<RangeSetBlaze<u32>>,
2059        mask: Arc<[u64]>,
2060    ) -> DenseTokenMaskCache {
2061        let mut precomputed: FxHashMap<usize, Arc<[u64]>> = FxHashMap::default();
2062        precomputed.insert(Arc::as_ptr(token_set) as usize, mask);
2063        precomputed
2064    }
2065
2066    fn mask_contains(mask: &[u32], token: u32) -> bool {
2067        mask.get(token as usize / 32)
2068            .is_some_and(|word| word & (1u32 << (token % 32)) != 0)
2069    }
2070
2071    #[test]
2072    fn component_mask_word_copy_matches_exact_membership_dense_sparse_and_specials() {
2073        // Dense prefixes ending on and between word boundaries; sparse holes;
2074        // byte aliases; out-of-vocabulary specials; and longer output buffers.
2075        let vocabularies = [
2076            (0..2).collect::<Vec<u32>>(),
2077            (0..32).collect::<Vec<u32>>(),
2078            (0..35).collect::<Vec<u32>>(),
2079            vec![0, 3, 31, 32, 65, 96],
2080        ];
2081        for ids in vocabularies {
2082            let vocab = Vocab::from_entries_unchecked(ids.iter().map(|&id| (id, b"a".to_vec())).collect());
2083            let original = crate::ConstraintSpec::builder(
2084                Grammar::glrm("glrm 1; start document; extern token SPECIAL; nt document = \"a\" | SPECIAL;"),
2085                &vocab,
2086            ).unwrap().bind_token("SPECIAL", [70, 130]).unwrap().build().unwrap().compile().unwrap();
2087            let loaded = Constraint::load(original.save(), &vocab).unwrap();
2088            for constraint in [&original, &loaded] {
2089                let state = constraint.start();
2090                for seed in [0u32, 0x5555_5555, 0xffff_ffff] {
2091                    let mut actual = vec![seed; constraint.mask_bit_len().div_ceil(32) + 2];
2092                    let mut expected = actual.clone();
2093                    let source: Vec<_> = (0..actual.len() + 1)
2094                        .map(|i| if seed == 0 { u32::MAX } else { seed.rotate_left(i as u32) })
2095                        .collect();
2096                    for (word, (&bits, output)) in source.iter().zip(&mut expected).enumerate() {
2097                        for bit in 0..32 {
2098                            if bits & (1u32 << bit) != 0 && state.knows_token_id(word as u32 * 32 + bit) {
2099                                *output |= 1u32 << bit;
2100                            }
2101                        }
2102                    }
2103                    state.or_segmented_component_mask(&mut actual, &source);
2104                    assert_eq!(actual, expected, "ids={ids:?}, seed={seed}");
2105                }
2106            }
2107        }
2108    }
2109
2110    #[test]
2111    fn segmented_static_result_cache_tracks_exact_scoped_state() {
2112        let vocab = Vocab::from_entries_unchecked(vec![
2113            (0, b"[".to_vec()), (1, b"a".to_vec()), (2, b"]".to_vec()),
2114            (3, b"!".to_vec()), (4, b"[aa]!".to_vec()), (5, b" ".to_vec()),
2115        ]);
2116        let child = Constraint::compile(Grammar::glrm(
2117            r#"start child; ignore WS; t WS = " "+; t WORD = /[a-z]+/; nt child = WORD;"#
2118        ), &vocab).unwrap();
2119        let parent = Constraint::compile(Grammar::glrm(
2120            r#"start document; extern grammar child; nt document = "[" child "]!";"#
2121        ), &vocab).unwrap();
2122        let bound = parent.bind_grammar("child", child).unwrap();
2123        assert!(bound.uses_compact_segmented_parser_runtime());
2124        let loaded = Constraint::load(bound.save(), &vocab).unwrap();
2125        for constraint in [&bound, &loaded] {
2126            let mut state = constraint.start();
2127            let mut unchanged_cache_reuses = 0;
2128            for token in [0,1,1,1,5,2,3] {
2129                let mask = state.mask();
2130                assert!(mask_contains(&mask, token));
2131                let mut cached = vec![0; mask.len()];
2132                assert!(state.try_fill_mask_from_cache(&mut cached));
2133                assert_eq!(cached, mask);
2134                let before = state.state.clone();
2135                assert!(state.commit_token(token));
2136                if before == state.state {
2137                    assert!(state.try_fill_mask_from_cache(&mut cached));
2138                    unchanged_cache_reuses += 1;
2139                } else {
2140                    assert!(!state.try_fill_mask_from_cache(&mut cached));
2141                }
2142                assert_eq!(state.mask(), state.clone().mask(), "cached/fresh token={token}");
2143            }
2144            assert!(unchanged_cache_reuses > 0, "fixture must exercise a repeated-state cache hit");
2145            assert!(state.is_accepting());
2146            assert!(!state.commit_token(0));
2147            assert!(state.mask().iter().all(|&word| word == 0), "failed commit invalidates cache");
2148            assert_eq!(state.mask(), state.clone().mask());
2149        }
2150    }
2151
2152
2153    fn exact_start_trigger_contains(constraint: &Constraint, token: u32) -> bool {
2154        let crate::runtime::BoundaryTrigger::Exact(dwa) = &constraint.boundary_trigger else {
2155            panic!("constraint does not carry an Exact boundary trigger");
2156        };
2157        let state = constraint.start();
2158        let mut accepted = false;
2159        for (&tokenizer_state, gss) in state.state.iter() {
2160            let complete = gss.for_each_stack_top_first_bounded(128, |top_first, _| {
2161                let weight =
2162                    exact_component_trigger_accepted_weight(constraint, dwa, top_first);
2163                if weight.tokens_for_tsid(tokenizer_state).contains(token) {
2164                    accepted = true;
2165                }
2166            });
2167            assert!(complete, "tiny trigger test GSS traversal must complete");
2168        }
2169        accepted
2170    }
2171
2172    #[test]
2173    fn exact_finish_trigger_requires_a_proper_internal_offset() {
2174        let vocab = Vocab::from_entries_unchecked(vec![
2175            (0, b"x".to_vec()),
2176            (1, b"xy".to_vec()),
2177            (2, b"xx".to_vec()),
2178            (3, b"yx".to_vec()),
2179        ]);
2180        let mut constraint = Constraint::from_ebnf(r#"start ::= "x""#, &vocab).unwrap();
2181        constraint.build_exact_boundary_trigger().unwrap();
2182
2183        assert!(exact_start_trigger_contains(&constraint, 1));
2184        assert!(exact_start_trigger_contains(&constraint, 2));
2185        assert!(
2186            !exact_start_trigger_contains(&constraint, 0),
2187            "finish exactly at model-token end is not an internal trigger",
2188        );
2189        assert!(!exact_start_trigger_contains(&constraint, 3));
2190    }
2191
2192    #[test]
2193    fn exact_entry_trigger_requires_placeholder_readiness_after_prefix() {
2194        let vocab = Vocab::from_entries_unchecked(vec![
2195            (0, b"x".to_vec()),
2196            (1, b"xy".to_vec()),
2197            (2, b"y".to_vec()),
2198        ]);
2199        let mut parent = Constraint::from_glrm_grammar_with_unbound_subgrammars_bindings_and_end_tokens(
2200            "glrm 1; start start; extern grammar child; nt start = \"x\" child;",
2201            &vocab,
2202            &[],
2203            &[],
2204        )
2205        .unwrap();
2206        parent.build_exact_boundary_trigger().unwrap();
2207
2208        assert!(exact_start_trigger_contains(&parent, 1));
2209        assert!(
2210            !exact_start_trigger_contains(&parent, 0),
2211            "placeholder reached only at model-token end is handled by next-call control closure",
2212        );
2213        assert!(!exact_start_trigger_contains(&parent, 2));
2214    }
2215
2216    #[test]
2217    fn recursive_exact_full_walk_ignores_outer_table_and_tokenizer() {
2218        let vocab = Vocab::from_entries_unchecked(vec![
2219            (0, b"X".to_vec()),
2220            (1, b"a".to_vec()),
2221            (2, b"!".to_vec()),
2222            (3, b"Xa!".to_vec()),
2223            (4, b"a!".to_vec()),
2224        ]);
2225        let child = Constraint::compile(
2226            Grammar::glrm("glrm 1; start child; nt child = \"a\";"),
2227            &vocab,
2228        )
2229        .unwrap();
2230        let parent = Constraint::compile(
2231            Grammar::glrm(
2232                "glrm 1; start document; extern grammar child; nt document = \"X\" child \"!\";",
2233            ),
2234            &vocab,
2235        )
2236        .unwrap();
2237        let bound = parent
2238            .bind_grammar_dynamic_boundary("child", child)
2239            .unwrap();
2240        let monolithic = Constraint::compile(
2241            Grammar::glrm("glrm 1; start document; nt document = \"X\" \"a\" \"!\";"),
2242            &vocab,
2243        )
2244        .unwrap();
2245
2246        let mut poisoned = Constraint::load(bound.save(), &vocab).unwrap();
2247        poisoned.recursive_parser_layout().unwrap().unwrap();
2248        let root = poisoned
2249            .static_dynamic_overlay
2250            .as_ref()
2251            .unwrap()
2252            .segmented_parser_components[0]
2253            .constraint
2254            .clone();
2255        poisoned.tokenizer = root.tokenizer.clone();
2256        poisoned.tokenizer_fast_transitions = root.tokenizer_fast_transitions.clone();
2257        poisoned.tokenizer_has_epsilon_transitions = root.tokenizer_has_epsilon_transitions;
2258        assert!(!poisoned.table.is_present(), "native root must retain no LR table");
2259
2260        let mut actual = poisoned.start();
2261        let mut expected = monolithic.start();
2262        for prefix_token in [None, Some(0), Some(1)] {
2263            if let Some(token) = prefix_token {
2264                assert!(actual.commit_token(token));
2265                assert!(expected.commit_token(token));
2266            }
2267            let mut fallback = vec![0u32; poisoned.body_mask_len()];
2268            actual.fill_recursive_mask_by_exact_full_walk(&mut fallback);
2269            let expected_mask = expected.mask();
2270            assert_eq!(fallback, expected_mask);
2271
2272            let mut dynamic_reference = vec![0u32; poisoned.body_mask_len()];
2273            actual.fill_mask_dynamic(&mut dynamic_reference);
2274            assert_eq!(dynamic_reference, expected_mask);
2275
2276            let mut profiled = vec![0u32; poisoned.body_mask_len()];
2277            actual.fill_mask_profiled(&mut profiled);
2278            assert_eq!(profiled, expected_mask);
2279        }
2280    }
2281
2282    /// The former recursive walker deliberately scanned dead descendants.
2283    /// Keep that independent control flow as a regression oracle for DFS jumps.
2284    fn recursive_unpruned_reference(state: &super::ConstraintState) -> Vec<u32> {
2285        let vocab = state.constraint.dynamic_mask_vocab_for_runtime();
2286        let trie = vocab.trie.as_ref();
2287        let mut buffers = super::CommitBuffers::default();
2288        let mut output = vec![0u32; state.constraint.mask_bit_len().div_ceil(32)];
2289        let mut stack = vec![None; usize::from(trie.full_walk_max_parent_depth()) + 2];
2290        stack[0] = Some(state.state.clone());
2291        let mark = |node, output: &mut [u32]| {
2292            if let Some(canonical) = trie.node(node).token_id {
2293                for &id in vocab.token_ids(canonical).unwrap() {
2294                    if !state.constraint.has_special_token_id(id) {
2295                        super::set_original_mask_bit(output, id);
2296                    }
2297                }
2298            }
2299        };
2300        // The root's zero-byte aliases are not model-token byte transitions.
2301        // Exact special-token paths for those IDs are evaluated below.
2302        for edge in trie.walk_edges() {
2303            let depth = edge.parent_depth as usize;
2304            let next = stack[depth].as_ref().and_then(|parent| {
2305                crate::runtime::commit::advance_bytes_from_state_exact(
2306                    &state.constraint, parent, &mut buffers, trie.walk_edge_bytes(edge),
2307                )
2308            });
2309            if next.is_some() {
2310                mark(edge.child, &mut output);
2311            }
2312            stack[depth + 1] = next;
2313        }
2314        for special in &state.constraint.special_token_terminals {
2315            if state.constraint.is_late_grammar_placeholder_terminal(special.terminal_id) { continue; }
2316            for token in special.token_ids() {
2317                if recursive_token_domain_reference(state, &mut buffers, token) {
2318                    super::set_original_mask_bit(&mut output, token);
2319                }
2320            }
2321        }
2322        output
2323    }
2324
2325    fn recursive_token_domain_reference(
2326        state: &super::ConstraintState,
2327        buffers: &mut super::CommitBuffers,
2328        token_id: u32,
2329    ) -> bool {
2330        if state.constraint.token_bytes_for_id(token_id).is_some_and(|b| b.is_empty()) {
2331            // commit_bytes(empty) is intentionally a no-op; it is not a proof
2332            // of model-token admission. Match the explicit current public API
2333            // contract without suppressing any nonempty or special-ID probes.
2334            state.constraint.has_special_token_id(token_id)
2335                && crate::runtime::commit::advance_special_token_paths(
2336                    &state.constraint, &state.state, token_id,
2337                ).is_some_and(|gss| !gss.is_empty())
2338        } else {
2339            crate::runtime::commit::token_admissible_from_state_exact(
2340                &state.constraint, &state.state, buffers, token_id,
2341            )
2342        }
2343    }
2344
2345    #[test]
2346    fn recursive_dead_subtree_jumps_match_unpruned_and_pointwise_oracles() {
2347        // Large dead families share ancestors with live siblings. Duplicate
2348        // byte spellings, an empty token, and a special-token spelling within
2349        // a dead byte family exercise independent endpoint/semantic routing.
2350        let mut entries = vec![
2351            (0, b"X".to_vec()), (1, b"[".to_vec()), (2, b"a".to_vec()),
2352            (3, b"]".to_vec()), (4, b"!".to_vec()), (5, b"a]!".to_vec()),
2353            (6, b"[a]!".to_vec()), (7, b"X[a]!".to_vec()),
2354            (8, b"X[]!".to_vec()), (9, Vec::new()), (10, b"a".to_vec()),
2355            (11, b"qdead-special".to_vec()), (12, b"qdead-special".to_vec()),
2356            (13, b"]!".to_vec()), (14, b"[]!".to_vec()),
2357        ];
2358        for i in 0..512u32 {
2359            entries.push((32 + i, format!("qdead-{i:04}-suffix").into_bytes()));
2360            entries.push((600 + i, format!("X[ab-{i:04}-suffix").into_bytes()));
2361        }
2362        let ids: Vec<u32> = entries.iter().map(|(id, _)| *id).chain([9001]).collect();
2363        let vocab = Vocab::from_entries_unchecked(entries);
2364        for nullable in [false, true] {
2365            let leaf_source = if nullable {
2366                "glrm 1; start leaf; extern token SPECIAL; nt leaf = \"a\"? | SPECIAL;"
2367            } else {
2368                "glrm 1; start leaf; extern token SPECIAL; nt leaf = \"a\" | SPECIAL;"
2369            };
2370            let leaf = crate::ConstraintSpec::builder(Grammar::glrm(leaf_source), &vocab)
2371                .unwrap().bind_token("SPECIAL", [11, 9001]).unwrap()
2372                .build().unwrap().compile().unwrap();
2373            let middle_parent = Constraint::compile(Grammar::glrm(
2374                "glrm 1; start middle; extern grammar leaf; nt middle = \"[\" leaf \"]\";",
2375            ), &vocab).unwrap();
2376            let middle = middle_parent.bind_grammar_dynamic_boundary("leaf", leaf).unwrap();
2377            let outer_parent = Constraint::compile(Grammar::glrm(
2378                "glrm 1; start outer; extern grammar middle; nt outer = \"X\" middle \"!\";",
2379            ), &vocab).unwrap();
2380            let bound = outer_parent.bind_grammar_dynamic_boundary("middle", middle).unwrap();
2381            let loaded = Constraint::load(bound.save(), &vocab).unwrap();
2382            for constraint in [&bound, &loaded] {
2383                assert!(constraint.uses_compact_segmented_parser_runtime());
2384                let check = |state: &super::ConstraintState| {
2385                    let mut actual = vec![0u32; constraint.mask_bit_len().div_ceil(32)];
2386                    state.fill_recursive_mask_by_exact_full_walk(&mut actual);
2387                    assert_eq!(actual, recursive_unpruned_reference(state), "nullable={nullable}");
2388                    for budget in [0, 1, 2] {
2389                        let mut bounded = vec![0u32; constraint.mask_bit_len().div_ceil(32)];
2390                        state.or_recursive_dynamic_full_walk_exact_with_budget(&mut bounded, budget);
2391                        assert_eq!(bounded, actual, "cache budget={budget}, nullable={nullable}");
2392                    }
2393                    let mut buffers = super::CommitBuffers::default();
2394                    for &id in &ids {
2395                        let exact = recursive_token_domain_reference(state, &mut buffers, id);
2396                        let allowed = actual[id as usize / 32] & (1 << (id % 32)) != 0;
2397                        assert_eq!(allowed, exact, "token={id}, nullable={nullable}");
2398                    }
2399                    assert_eq!(state.mask(), actual);
2400                };
2401                for prefix in [b"".as_slice(), b"X", b"X[", b"X[a", b"X[a]", b"X[a]!"] {
2402                    let mut state = constraint.start();
2403                    assert!(state.commit_bytes(prefix));
2404                    check(&state);
2405                }
2406                for special in [11, 9001] {
2407                    let mut state = constraint.start();
2408                    assert!(state.commit_bytes(b"X["));
2409                    let mask = state.mask();
2410                    assert_ne!(mask[special / 32] & (1 << (special % 32)), 0);
2411                    assert_eq!(mask[0] & (1 << 12), 0, "byte alias has no special route");
2412                    assert!(state.commit_token(special as u32));
2413                    check(&state);
2414                    assert!(state.commit_bytes(b"]!"));
2415                    check(&state);
2416                }
2417                if nullable {
2418                    let mut state = constraint.start();
2419                    assert!(state.commit_bytes(b"X[]!"));
2420                    check(&state);
2421                }
2422            }
2423        }
2424    }
2425
2426    #[test]
2427    fn recursive_transition_cache_matches_radix_on_text_and_ambiguity() {
2428        let mut words = vec![Vec::<u8>::new()];
2429        let mut layer = vec![Vec::<u8>::new()];
2430        for _ in 0..4 {
2431            let mut next = Vec::new();
2432            for prefix in layer {
2433                for &byte in b"abcX[]! " {
2434                    let mut word = prefix.clone();
2435                    word.push(byte);
2436                    next.push(word);
2437                }
2438            }
2439            words.extend(next.iter().cloned());
2440            layer = next;
2441        }
2442        let vocab = Vocab::from_entries_unchecked(words.into_iter().enumerate()
2443            .map(|(id, bytes)| (id as u32, bytes)).collect::<Vec<_>>());
2444        for leaf_source in [
2445            "glrm 1; start leaf; t TEXT = /[a-c ]{1,8}/; nt leaf = TEXT;",
2446            "glrm 1; start leaf; t WORD = /[a-c]{1,4}/; nt leaf = WORD | WORD WORD;",
2447            "glrm 1; start leaf; ignore WS; t WS = \" \"+; t WORD = /[a-c]{1,4}/; nt leaf = WORD;",
2448        ] {
2449            let leaf = Constraint::compile(Grammar::glrm(leaf_source), &vocab).unwrap();
2450            let middle = Constraint::compile(Grammar::glrm(
2451                "glrm 1; start middle; extern grammar leaf; nt middle = \"[\" leaf \"]\";",
2452            ), &vocab).unwrap().bind_grammar_dynamic_boundary("leaf", leaf).unwrap();
2453            let bound = Constraint::compile(Grammar::glrm(
2454                "glrm 1; start outer; extern grammar middle; nt outer = \"X\" middle \"!\";",
2455            ), &vocab).unwrap().bind_grammar_dynamic_boundary("middle", middle).unwrap();
2456            let alphabet = super::recursive_mask_byte_representatives(&bound);
2457            assert_eq!(alphabet[b'a' as usize], alphabet[b'b' as usize]);
2458            assert_eq!(alphabet[b'b' as usize], alphabet[b'c' as usize]);
2459            assert_ne!(alphabet[b'a' as usize], alphabet[b']' as usize]);
2460            for prefix in [b"".as_slice(), b"X", b"X[", b"X[a", b"X[abc", b"X[abc]", b"X[abc]!"] {
2461                let mut state = bound.start();
2462                assert!(state.commit_bytes(prefix));
2463                let expected = recursive_unpruned_reference(&state);
2464                for budget in [0, 2, 256] {
2465                    let mut actual = vec![0u32; bound.mask_bit_len().div_ceil(32)];
2466                    state.or_recursive_dynamic_full_walk_exact_with_budget(&mut actual, budget);
2467                    assert_eq!(actual, expected, "prefix={prefix:?} budget={budget} leaf={leaf_source}");
2468                }
2469            }
2470        }
2471    }
2472
2473    #[test]
2474    fn precomputed_dense_intersection_reuses_arc_when_unchanged() {
2475        let dense: Arc<[u64]> = Arc::from([0b1011_u64, 0b0101]);
2476        let token_set = Arc::new(RangeSetBlaze::from_iter(std::iter::once(0_u32..=127)));
2477        let precomputed = precomputed_for(&token_set, Arc::from([!0_u64, !0_u64]));
2478
2479        let mut cache = FxHashMap::default();
2480        let intersected = DenseMaskAcc::intersect_dense_with_token_set_cached(
2481            0,
2482            &dense,
2483            &token_set,
2484            &precomputed,
2485            &mut cache,
2486        )
2487        .unwrap();
2488
2489        assert!(Arc::ptr_eq(&intersected, &dense));
2490    }
2491
2492    #[test]
2493    fn precomputed_dense_intersection_allocates_when_pruned() {
2494        let dense: Arc<[u64]> = Arc::from([0b1011_u64, 0b0101]);
2495        let token_set = Arc::new(RangeSetBlaze::from_iter(std::iter::once(0_u32..=127)));
2496        let precomputed = precomputed_for(&token_set, Arc::from([0b0011_u64, 0b0000]));
2497
2498        let mut cache = FxHashMap::default();
2499        let intersected = DenseMaskAcc::intersect_dense_with_token_set_cached(
2500            0,
2501            &dense,
2502            &token_set,
2503            &precomputed,
2504            &mut cache,
2505        )
2506        .unwrap();
2507
2508        assert!(!Arc::ptr_eq(&intersected, &dense));
2509        assert_eq!(&*intersected, &[0b0011_u64, 0b0000]);
2510    }
2511
2512    #[test]
2513    fn small_intersection_cache_reuses_exact_result() {
2514        let dense: Arc<[u64]> = Arc::from([0b1011_u64, 0b0101]);
2515        let token_set = Arc::new(RangeSetBlaze::from_iter(std::iter::once(0_u32..=127)));
2516        let precomputed = precomputed_for(&token_set, Arc::from([0b0011_u64, 0b0100]));
2517        let mut cache = DenseTokenSetIntersectionSmallCache::new();
2518
2519        let first = DenseMaskAcc::intersect_dense_with_token_set_small_cached(
2520            &dense,
2521            &token_set,
2522            &precomputed,
2523            &mut cache,
2524        )
2525        .unwrap();
2526        let second = DenseMaskAcc::intersect_dense_with_token_set_small_cached(
2527            &dense,
2528            &token_set,
2529            &precomputed,
2530            &mut cache,
2531        )
2532        .unwrap();
2533
2534        assert_eq!(&*first, &[0b0011_u64, 0b0100]);
2535        assert!(Arc::ptr_eq(&first, &second));
2536        assert_eq!(cache.len(), 1);
2537        assert!(Arc::ptr_eq(&cache[0].0, &dense));
2538    }
2539
2540    #[test]
2541    fn empty_possible_matches_uses_exact_seed_exclusion_scan() {
2542        let mut constraint = Constraint::from_glrm_grammar(
2543            r#"
2544                start start;
2545                t A = "a";
2546                t B = "b";
2547                nt start = A | B;
2548            "#,
2549            &Vocab::from_entries_unchecked(
2550                vec![
2551                    (0, b"a".to_vec()),
2552                    (1, b"b".to_vec()),
2553                    (2, b"ab".to_vec()),
2554                ]),
2555        )
2556        .expect("test constraint should compile");
2557        let terminal_a = constraint
2558            .terminal_display_names
2559            .iter()
2560            .position(|name| name == "A")
2561            .expect("A terminal should have a display name") as u32;
2562        constraint.possible_matches.clear();
2563        constraint.possible_matches_complete = false;
2564
2565        let tokenizer_state = constraint.tokenizer.initial_state();
2566        let disallowed = TerminalsDisallowed::new().with_insert(tokenizer_state, terminal_a);
2567        let mut state = constraint.start_dynamic();
2568        state.state = crate::runtime::state::ParserStateMap::singleton(
2569            tokenizer_state,
2570            ParserGSS::from_stacks(&[(vec![0u32], disallowed)]),
2571        );
2572
2573        let mut expected = vec![0u32; constraint.body_mask_len()];
2574        state.fill_mask_dynamic(&mut expected);
2575        let mut actual = vec![0u32; constraint.body_mask_len()];
2576        state.fill_mask(&mut actual);
2577        assert_eq!(actual, expected);
2578
2579        let loaded = Constraint::load(constraint.save(), &crate::public_api::constraint_vocab(&constraint)).expect("empty-PM constraint should roundtrip");
2580        assert!(loaded.possible_matches.is_empty());
2581        let mut loaded_state = loaded.start_dynamic();
2582        let loaded_tokenizer_state = loaded.tokenizer.initial_state();
2583        let loaded_disallowed =
2584            TerminalsDisallowed::new().with_insert(loaded_tokenizer_state, terminal_a);
2585        loaded_state.state = crate::runtime::state::ParserStateMap::singleton(
2586            loaded_tokenizer_state,
2587            ParserGSS::from_stacks(&[(vec![0u32], loaded_disallowed)]),
2588        );
2589        let mut loaded_expected = vec![0u32; loaded.body_mask_len()];
2590        loaded_state.fill_mask_dynamic(&mut loaded_expected);
2591        let mut loaded_actual = vec![0u32; loaded.body_mask_len()];
2592        loaded_state.fill_mask(&mut loaded_actual);
2593        assert_eq!(loaded_actual, loaded_expected);
2594    }
2595
2596    #[test]
2597    fn literal_choice_terminal_mask_keeps_multibyte_prefix_tokens() {
2598        let vocab = Vocab::from_entries_unchecked(vec![
2599            (0, b"\"".to_vec()),
2600            (1, b"S".to_vec()),
2601            (2, b"Se".to_vec()),
2602            (3, b"Service".to_vec()),
2603            (4, b"I".to_vec()),
2604            (5, b"In".to_vec()),
2605            (6, b"Independent".to_vec()),
2606            (7, b" provider assertion\"".to_vec()),
2607            (8, b" validation of assertion\"".to_vec()),
2608        ]);
2609        let constraint = Constraint::from_glrm_grammar(
2610            r#"
2611                start start;
2612                nt assurance_body = fa {
2613                    start 0;
2614                    accept 1;
2615                    edge 0 -> 1: "\"" ("Service provider assertion\"" | "Independent validation of assertion\"");
2616                };
2617                nt start = assurance_body;
2618            "#,
2619            &vocab,
2620        )
2621        .expect("literal-choice terminal should compile");
2622
2623        let mut state = constraint.start();
2624        assert!(state.commit_token(0), "opening quote should commit");
2625
2626        let mut static_mask = vec![0u32; constraint.body_mask_len()];
2627        state.fill_mask(&mut static_mask);
2628        let mut dynamic_mask = vec![0u32; constraint.body_mask_len()];
2629        state.fill_mask_dynamic(&mut dynamic_mask);
2630
2631        assert_eq!(static_mask, dynamic_mask);
2632        for token in [1, 2, 3, 4, 5, 6] {
2633            assert!(
2634                mask_contains(&static_mask, token),
2635                "literal prefix token {token} should be accepted"
2636            );
2637        }
2638    }
2639
2640    #[test]
2641    fn direct_mask_spills_past_the_inline_path_capacity() {
2642        let vocab = Vocab::from_entries_unchecked(vec![(0, b"a".to_vec()), (1, b"b".to_vec())]);
2643        let constraint = Constraint::from_glrm_grammar(
2644            r#"
2645                start start;
2646                t A = "a";
2647                nt start = A;
2648            "#,
2649            &vocab,
2650        )
2651        .expect("single-terminal grammar should compile");
2652        let mut state = constraint.start();
2653        let (tokenizer_state, parser_gss) = state.state.entries[0].clone();
2654        state.state.entries.clear();
2655        for _ in 0..=MASK_SINGLE_PATH_DIRECT_INLINE_PATH_CAPACITY {
2656            state
2657                .state
2658                .insert_flat_alternative(tokenizer_state, parser_gss.clone());
2659        }
2660        assert_eq!(
2661            state.state.len(),
2662            MASK_SINGLE_PATH_DIRECT_INLINE_PATH_CAPACITY + 1,
2663        );
2664
2665        let mut direct = vec![0u32; constraint.body_mask_len()];
2666        assert!(state.try_fill_mask_single_path_direct(&mut direct));
2667        let mut dynamic = vec![0u32; constraint.body_mask_len()];
2668        state.fill_mask_dynamic(&mut dynamic);
2669        assert_eq!(direct, dynamic);
2670        assert!(mask_contains(&direct, 0));
2671        assert!(!mask_contains(&direct, 1));
2672    }
2673
2674    #[test]
2675    fn direct_mask_declines_wide_shared_gss_without_partial_output() {
2676        let vocab = Vocab::from_entries_unchecked(vec![(0, b"a".to_vec()), (1, b"b".to_vec())]);
2677        let constraint = Constraint::from_glrm_grammar(
2678            r#"start start; t A = "a"; nt start = A;"#,
2679            &vocab,
2680        )
2681        .expect("routing-test grammar should compile");
2682        let mut state = constraint.start();
2683        let tokenizer_state = state.state.entries[0].0;
2684        // Deliberately synthetic parser labels: admission must decline BEFORE
2685        // looking up any of them or evaluating an incomplete subset of paths.
2686        // Both the one-pass and the many-lexer two-pass admission paths matter.
2687        let wide = ParserGSS::from_stacks(
2688            &(0..=MASK_SINGLE_PATH_DIRECT_MAX_PATHS_PER_GSS)
2689                .map(|path| (vec![0, 10_000 + path as u32, 7], TerminalsDisallowed::default()))
2690                .collect::<Vec<_>>(),
2691        );
2692        for lexer_branches in [1, MASK_SINGLE_PATH_DIRECT_INLINE_PATH_CAPACITY] {
2693            state.state.entries.clear();
2694            for _ in 0..lexer_branches {
2695                state.state.insert_flat_alternative(tokenizer_state, wide.clone());
2696            }
2697            let mut mask = vec![0x5a5a_5a5a; constraint.body_mask_len()];
2698            let before = mask.clone();
2699            assert!(!state.try_fill_mask_single_path_direct(&mut mask));
2700            assert_eq!(mask, before, "declining admission must not publish a partial mask");
2701        }
2702    }
2703
2704    #[test]
2705    fn stack_plan_admission_depends_on_reuse_not_the_old_path_boundary() {
2706        for path_count in [31, 32, 33, 64] {
2707            assert!(!single_path_direct_plan_reuse_dominates(
2708                path_count,
2709                path_count * 8,
2710                0,
2711            ));
2712        }
2713        assert!(!single_path_direct_plan_reuse_dominates(2, 16, 8));
2714        assert!(!single_path_direct_plan_reuse_dominates(3, 24, 16));
2715        assert!(!single_path_direct_plan_reuse_dominates(9, 72, 56));
2716        assert!(single_path_direct_plan_reuse_dominates(9, 144, 112));
2717    }
2718
2719    #[test]
2720    fn single_path_direct_stack_work_budget_accepts_shallow_ambiguity() {
2721        assert_eq!(single_path_direct_stack_work([8; 10]), Some(80));
2722        assert_eq!(
2723            single_path_direct_stack_work([MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_STACK_VALUES]),
2724            Some(MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_STACK_VALUES),
2725        );
2726        assert_eq!(
2727            single_path_direct_stack_work([
2728                MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_STACK_VALUES,
2729                1,
2730            ]),
2731            None,
2732        );
2733    }
2734
2735    #[test]
2736    fn indexed_dag_mask_matches_dynamic_on_all_small_reachable_states() {
2737        use std::collections::BTreeSet;
2738        fn allowed(mask: &[u32], token: u32) -> bool {
2739            mask.get(token as usize / 32)
2740                .is_some_and(|word| word & (1u32 << (token % 32)) != 0)
2741        }
2742
2743        let vocab = Vocab::from_entries_unchecked(
2744            ["a", "b", "ab", "ba", "aa", "bb"]
2745                .into_iter()
2746                .enumerate()
2747                .map(|(id, bytes)| (id as u32, bytes.as_bytes().to_vec()))
2748                .collect(),
2749        );
2750        let grammars = [
2751            r#"
2752                start start;
2753                t A = "a" | "ab";
2754                t B = "a" | "ba";
2755                nt item = A | B;
2756                nt start = item item? item?;
2757            "#,
2758            r#"
2759                start start;
2760                t A = "a"+;
2761                t B = "a"+ "b"?;
2762                nt start = A A | B B | A B | B A;
2763            "#,
2764        ];
2765
2766        let mut ambiguous_states = 0usize;
2767        for grammar in grammars {
2768            let constraint = Constraint::from_glrm_grammar(grammar, &vocab)
2769                .expect("small indexed-DAG parity grammar should compile");
2770            let mut frontier = vec![(constraint.start(), Vec::<u32>::new())];
2771            let mut seen = BTreeSet::new();
2772            for depth in 0..=3 {
2773                let mut next = Vec::new();
2774                for (state, path) in frontier {
2775                    let key = state.debug_parser_stacks();
2776                    if !seen.insert(format!("{key:?}")) {
2777                        continue;
2778                    }
2779                    let mut expected = vec![0u32; constraint.body_mask_len()];
2780                    state.fill_mask_dynamic(&mut expected);
2781                    if state.has_parser_ambiguity() {
2782                        ambiguous_states += 1;
2783                        let mut actual = vec![0u32; constraint.body_mask_len()];
2784                        assert!(state.fill_mask_indexed_dag(&mut actual, true));
2785                        assert_eq!(
2786                            actual, expected,
2787                            "indexed/dynamic mask mismatch depth={depth} path={path:?} grammar={grammar}"
2788                        );
2789                    }
2790                    if depth == 3 {
2791                        continue;
2792                    }
2793                    for (token, bytes) in constraint.token_bytes_iter() {
2794                        if !allowed(&expected, token) {
2795                            continue;
2796                        }
2797                        let mut advanced = state.clone();
2798                        assert!(advanced
2799                            .commit_bytes(bytes), "dynamically admitted token must commit");
2800                        let mut next_path = path.clone();
2801                        next_path.push(token);
2802                        next.push((advanced, next_path));
2803                    }
2804                }
2805                frontier = next;
2806            }
2807        }
2808        assert!(ambiguous_states > 0, "test must exercise indexed ambiguous states");
2809    }
2810
2811    #[test]
2812    fn indexed_dag_cache_stays_exact_across_commits_and_restore() {
2813        let vocab = Vocab::from_entries_unchecked(
2814            ["a", "b", "ab", "ba", "aa", "bb"]
2815                .into_iter()
2816                .enumerate()
2817                .map(|(id, bytes)| (id as u32, bytes.as_bytes().to_vec()))
2818                .collect(),
2819        );
2820        let constraint = Constraint::from_glrm_grammar(
2821            r#"
2822                start start;
2823                t A = "a"+;
2824                t B = "a"+ "b"?;
2825                nt item = A | B;
2826                nt start = item item? item? item?;
2827            "#,
2828            &vocab,
2829        )
2830        .expect("persistent indexed-DAG parity grammar should compile");
2831        let mut state = constraint.start();
2832        let sequence: [&[u8]; 4] = [b"a", b"a", b"a", b"b"];
2833        let mut checkpoint = None;
2834
2835        for (index, bytes) in sequence.into_iter().enumerate() {
2836            let mut expected = vec![0u32; constraint.body_mask_len()];
2837            state.fill_mask_dynamic(&mut expected);
2838            if state.has_parser_ambiguity() {
2839                let mut first = vec![0u32; constraint.body_mask_len()];
2840                let mut second = vec![0u32; constraint.body_mask_len()];
2841                assert!(state.fill_mask_indexed_dag(&mut first, true));
2842                assert!(state.fill_mask_indexed_dag(&mut second, true));
2843                assert_eq!(first, expected);
2844                assert_eq!(second, expected, "same-state cache hit changed the mask");
2845            }
2846            assert!(state
2847                .commit_bytes(bytes), "test sequence should remain valid");
2848            if index == 1 {
2849                checkpoint = Some(state.clone());
2850            }
2851        }
2852
2853        state = checkpoint.expect("checkpoint should be captured");
2854        let mut expected = vec![0u32; constraint.body_mask_len()];
2855        state.fill_mask_dynamic(&mut expected);
2856        if state.has_parser_ambiguity() {
2857            let mut actual = vec![0u32; constraint.body_mask_len()];
2858            assert!(state.fill_mask_indexed_dag(&mut actual, true));
2859            assert_eq!(actual, expected, "restored indexed mask diverged");
2860        }
2861    }
2862}
2863
2864impl Merge for DenseMaskAcc {
2865    fn merge(&self, other: &Self) -> Self {
2866        if self.is_empty() {
2867            return other.clone();
2868        }
2869        if other.is_empty() {
2870            return self.clone();
2871        }
2872
2873        if self.0.len() == 1 && other.0.len() == 1 {
2874            let (left_key, left_dense) = self.0.iter().next().expect("len checked");
2875            let (right_key, right_dense) = other.0.iter().next().expect("len checked");
2876            if left_key != right_key {
2877                let mut entries = SmallVec::new();
2878                if left_key < right_key {
2879                    entries.push((*left_key, Arc::clone(left_dense)));
2880                    entries.push((*right_key, Arc::clone(right_dense)));
2881                } else {
2882                    entries.push((*right_key, Arc::clone(right_dense)));
2883                    entries.push((*left_key, Arc::clone(left_dense)));
2884                }
2885                return Self(entries);
2886            }
2887            if Arc::ptr_eq(left_dense, right_dense) || left_dense == right_dense {
2888                return self.clone();
2889            }
2890            let len = left_dense.len().max(right_dense.len());
2891            let mut combined = vec![0u64; len];
2892            for (i, &word) in left_dense.iter().enumerate() {
2893                combined[i] |= word;
2894            }
2895            for (i, &word) in right_dense.iter().enumerate() {
2896                combined[i] |= word;
2897            }
2898            let mut entries = SmallVec::new();
2899            entries.push((*left_key, combined.into()));
2900            return Self(entries);
2901        }
2902
2903        let mut merged = self.0.clone();
2904
2905        for (tsid, other_dense) in &other.0 {
2906            match merged.iter().position(|(existing_tsid, _)| existing_tsid == tsid) {
2907                Some(idx) => {
2908                    let dense = &mut merged[idx].1;
2909                    let len = dense.len().max(other_dense.len());
2910                    let mut combined = vec![0u64; len];
2911
2912                    for (i, &word) in dense.iter().enumerate() {
2913                        combined[i] |= word;
2914                    }
2915                    for (i, &word) in other_dense.iter().enumerate() {
2916                        combined[i] |= word;
2917                    }
2918
2919                    *dense = combined.into();
2920                }
2921                None => {
2922                    let insert_at = merged
2923                        .iter()
2924                        .position(|(existing_tsid, _)| existing_tsid > tsid)
2925                        .unwrap_or(merged.len());
2926                    merged.insert(insert_at, (*tsid, Arc::clone(other_dense)));
2927                }
2928            }
2929        }
2930
2931        Self(merged)
2932    }
2933}
2934
2935#[derive(Clone, PartialEq, Eq, Hash)]
2936struct DenseAccIdentity(SmallVec<[(u32, usize, usize); 2]>);
2937
2938fn dense_acc_identity(accumulator: &DenseMaskAcc) -> DenseAccIdentity {
2939    DenseAccIdentity(
2940        accumulator
2941            .0
2942            .iter()
2943            .map(|(tsid, dense)| (*tsid, dense.as_ptr() as usize, dense.len()))
2944            .collect(),
2945    )
2946}
2947
2948#[derive(Clone)]
2949struct SingleLowerMemoEntry {
2950    dwa_state: u32,
2951    tsid: u32,
2952    result: Option<Arc<[u64]>>,
2953}
2954
2955#[derive(Clone)]
2956struct SingleSegmentMemoEntry {
2957    offset: usize,
2958    dwa_state: u32,
2959    tsid: u32,
2960    result: Option<Arc<[u64]>>,
2961}
2962
2963struct SingleSourceMemo {
2964    source: IndexedLowerIdentity<u32>,
2965    last_seen_epoch: u64,
2966    lower: SmallVec<[SingleLowerMemoEntry; 8]>,
2967    segments: SmallVec<[SingleSegmentMemoEntry; 8]>,
2968}
2969
2970#[derive(Default)]
2971pub(crate) struct IndexedDagMaskRuntime {
2972    epoch: u64,
2973    live_source_count: usize,
2974    lower_memo: FxHashMap<(u32, usize, u32), Option<DenseMaskAcc>>,
2975    segment_memo: FxHashMap<(usize, usize, u32, u32), Option<DenseMaskAcc>>,
2976    final_memo: FxHashMap<(u32, u32), Option<DenseMaskAcc>>,
2977    single_source_ids: FxHashMap<usize, u32>,
2978    single_sources: Vec<SingleSourceMemo>,
2979    lower_sources: FxHashMap<usize, IndexedLowerIdentity<u32>>,
2980    accumulators: Vec<DenseMaskAcc>,
2981    accumulator_ids: FxHashMap<DenseAccIdentity, u32>,
2982    index_nodes: Vec<IndexedLeveledGssNode<u32, DenseMaskAcc>>,
2983    index_roots: Vec<u32>,
2984    index_lower_ids: FxHashMap<usize, u32>,
2985    index_upper_ids: FxHashMap<usize, u32>,
2986}
2987
2988impl IndexedDagMaskRuntime {
2989    const SOURCE_SLACK: usize = 64;
2990    const MAX_ACCUMULATORS: usize = 65_536;
2991    const MAX_RETAINED_INDEX_NODES: usize = 16_384;
2992
2993    fn begin_mask(&mut self) {
2994        self.epoch = self.epoch.wrapping_add(1).max(1);
2995        self.live_source_count = 0;
2996        if self.accumulators.len() > Self::MAX_ACCUMULATORS {
2997            *self = Self {
2998                epoch: self.epoch,
2999                ..Self::default()
3000            };
3001        }
3002    }
3003
3004    fn mark_source_live(&mut self, slot: u32) {
3005        let source = &mut self.single_sources[slot as usize];
3006        if source.last_seen_epoch != self.epoch {
3007            source.last_seen_epoch = self.epoch;
3008            self.live_source_count += 1;
3009        }
3010    }
3011
3012    fn prune_stale_sources_if_needed(&mut self) {
3013        let threshold = self
3014            .live_source_count
3015            .saturating_mul(2)
3016            .saturating_add(Self::SOURCE_SLACK);
3017        if self.single_sources.len() <= threshold {
3018            return;
3019        }
3020        let oldest_kept = self.epoch.saturating_sub(1);
3021        self.single_sources
3022            .retain(|source| source.last_seen_epoch >= oldest_kept);
3023        self.single_source_ids.clear();
3024        let mut retained = FxHashSet::default();
3025        for (slot, source) in self.single_sources.iter().enumerate() {
3026            let ptr = source.source.ptr_key();
3027            retained.insert(ptr);
3028            self.single_source_ids.insert(
3029                ptr,
3030                u32::try_from(slot).expect("indexed mask source slots exceeded u32"),
3031            );
3032        }
3033        self.lower_sources.retain(|ptr, _| retained.contains(ptr));
3034        self.lower_memo
3035            .retain(|(_, ptr, _), _| retained.contains(ptr));
3036        self.segment_memo
3037            .retain(|(ptr, _, _, _), _| retained.contains(ptr));
3038    }
3039
3040    fn retain_index_scratch(
3041        &mut self,
3042        dag: IndexedLeveledGss<u32, DenseMaskAcc>,
3043        roots: Vec<u32>,
3044        lower_ids: FxHashMap<usize, u32>,
3045        upper_ids: FxHashMap<usize, u32>,
3046    ) {
3047        if dag.nodes.len() > Self::MAX_RETAINED_INDEX_NODES {
3048            return;
3049        }
3050        self.index_nodes = dag.nodes;
3051        self.index_roots = roots;
3052        self.index_lower_ids = lower_ids;
3053        self.index_upper_ids = upper_ids;
3054    }
3055}
3056
3057/// Exact denotational evaluator for the parser DWA over a weighted GSS DAG.
3058///
3059/// For DWA state `q`, GSS node `G`, and token accumulator `a`, the result is
3060///
3061/// `E(q, G, a) = union_{s in [[G]]} (a intersect W(q, s))`,
3062///
3063/// where `[[G]]` is the stack language denoted by the GSS node and `W(q, s)`
3064/// is the union of every accepting-prefix weight encountered while the parser
3065/// DWA reads stack `s` from the top downward.
3066///
3067/// The implementation is the structural recurrence of this definition:
3068///
3069/// * a branch is language union, so its result is bitmap union;
3070/// * an interface fixes the accumulator correlated with its lower language;
3071/// * a DWA edge `(q, x) -> (q', w)` contributes
3072///   `w intersect E(q', child, a)`;
3073/// * the current state's final weight contributes at every readable prefix;
3074/// * a segment is the unary instance of the same recurrence.
3075///
3076/// Exactness follows by induction on the acyclic indexed GSS DAG, using
3077/// distributivity of bitmap intersection over union. Memoization changes only
3078/// evaluation order; its key contains every semantic argument.
3079struct IndexedDagMaskEvaluator<'a, 'r> {
3080    constraint: &'a Constraint,
3081    dag: &'a IndexedLeveledGss<u32, DenseMaskAcc>,
3082    precomputed: &'a DenseTokenMaskCache,
3083    runtime: &'r mut IndexedDagMaskRuntime,
3084    source_slots: Vec<u32>,
3085    upper_memo: FxHashMap<(u32, u32), Option<DenseMaskAcc>>,
3086    all_upper_memo: FxHashMap<u32, Option<DenseMaskAcc>>,
3087    upper_calls: u64,
3088    upper_hits: u64,
3089    lower_calls: u64,
3090    lower_hits: u64,
3091    segment_calls: u64,
3092    segment_hits: u64,
3093    memo_result_entries: u64,
3094    memo_dense_words: u64,
3095    memo_nonzero_words: u64,
3096    memo_max_nonzero_words: u64,
3097}
3098
3099impl<'a, 'r> IndexedDagMaskEvaluator<'a, 'r> {
3100    fn new(
3101        constraint: &'a Constraint,
3102        dag: &'a IndexedLeveledGss<u32, DenseMaskAcc>,
3103        precomputed: &'a DenseTokenMaskCache,
3104        runtime: &'r mut IndexedDagMaskRuntime,
3105    ) -> Self {
3106        let source_slots = dag
3107            .nodes
3108            .iter()
3109            .map(|node| match node {
3110                IndexedLeveledGssNode::LowerGeneral { source, .. }
3111                | IndexedLeveledGssNode::LowerSegment { source, .. } => {
3112                    let ptr = source.ptr_key();
3113                    if let Some(&slot) = runtime.single_source_ids.get(&ptr) {
3114                        runtime.mark_source_live(slot);
3115                        slot
3116                    } else {
3117                        let slot = u32::try_from(runtime.single_sources.len())
3118                            .expect("indexed mask source slots exceeded u32");
3119                        runtime.single_sources.push(SingleSourceMemo {
3120                            source: source.clone(),
3121                            last_seen_epoch: runtime.epoch,
3122                            lower: SmallVec::new(),
3123                            segments: SmallVec::new(),
3124                        });
3125                        runtime.single_source_ids.insert(ptr, slot);
3126                        runtime.live_source_count += 1;
3127                        slot
3128                    }
3129                }
3130                IndexedLeveledGssNode::UpperBranch { .. }
3131                | IndexedLeveledGssNode::Interface { .. } => u32::MAX,
3132            })
3133            .collect();
3134        Self {
3135            constraint,
3136            dag,
3137            precomputed,
3138            runtime,
3139            source_slots,
3140            upper_memo: FxHashMap::default(),
3141            all_upper_memo: FxHashMap::default(),
3142            upper_calls: 0,
3143            upper_hits: 0,
3144            lower_calls: 0,
3145            lower_hits: 0,
3146            segment_calls: 0,
3147            segment_hits: 0,
3148            memo_result_entries: 0,
3149            memo_dense_words: 0,
3150            memo_nonzero_words: 0,
3151            memo_max_nonzero_words: 0,
3152        }
3153    }
3154
3155    fn accumulator_id(&mut self, accumulator: &DenseMaskAcc) -> u32 {
3156        let identity = dense_acc_identity(accumulator);
3157        if let Some(id) = self.runtime.accumulator_ids.get(&identity) {
3158            return *id;
3159        }
3160        let id = u32::try_from(self.runtime.accumulators.len())
3161            .expect("indexed DAG accumulator IDs exceeded u32");
3162        self.runtime.accumulators.push(accumulator.clone());
3163        self.runtime.accumulator_ids.insert(identity, id);
3164        id
3165    }
3166
3167    fn merge_result(current: &mut Option<DenseMaskAcc>, incoming: Option<DenseMaskAcc>) {
3168        let Some(incoming) = incoming else {
3169            return;
3170        };
3171        match current {
3172            Some(existing) => existing.merge_in_place(&incoming),
3173            None => *current = Some(incoming),
3174        }
3175    }
3176
3177    fn intersect_result(
3178        &self,
3179        result: Option<DenseMaskAcc>,
3180        weight: &Weight,
3181    ) -> Option<DenseMaskAcc> {
3182        result?.intersect_with_weight_reuse(weight, self.precomputed)
3183    }
3184
3185    fn final_for_accumulator(
3186        &mut self,
3187        dwa_state: u32,
3188        accumulator_id: u32,
3189    ) -> Option<DenseMaskAcc> {
3190        let key = (dwa_state, accumulator_id);
3191        if let Some(cached) = self.runtime.final_memo.get(&key) {
3192            return cached.clone();
3193        }
3194        let result = self.constraint.parser_dwa().states()[dwa_state as usize]
3195            .final_weight
3196            .as_ref()
3197            .and_then(|weight| {
3198                self.runtime.accumulators[accumulator_id as usize]
3199                    .intersect_with_weight_reuse(weight, self.precomputed)
3200            });
3201        self.runtime.final_memo.insert(key, result.clone());
3202        result
3203    }
3204
3205    fn all_accumulators_upper(&mut self, node: u32) -> Option<DenseMaskAcc> {
3206        if let Some(cached) = self.all_upper_memo.get(&node) {
3207            return cached.clone();
3208        }
3209        let indexed = self.dag.nodes[node as usize].clone();
3210        let mut out = None;
3211        match indexed {
3212            IndexedLeveledGssNode::UpperBranch { empty, children } => {
3213                Self::merge_result(&mut out, empty);
3214                for (_, child) in children {
3215                    Self::merge_result(&mut out, self.all_accumulators_upper(child));
3216                }
3217            }
3218            IndexedLeveledGssNode::Interface { accumulator, .. } => {
3219                out = Some(accumulator);
3220            }
3221            IndexedLeveledGssNode::LowerGeneral { .. }
3222            | IndexedLeveledGssNode::LowerSegment { .. } => {
3223                debug_assert!(false, "upper accumulator traversal reached lower node");
3224            }
3225        }
3226        self.all_upper_memo.insert(node, out.clone());
3227        out
3228    }
3229
3230    fn transition(&self, dwa_state: u32, parser_state: u32) -> Option<(u32, Weight)> {
3231        let transitions = &self.constraint.dwa_fast_transitions[dwa_state as usize];
3232        self.constraint
3233            .fast_parser_dwa_transition(transitions, parser_state)
3234            .map(|(target, weight)| (target, weight.clone()))
3235    }
3236
3237    fn eval_upper(&mut self, dwa_state: u32, node: u32) -> Option<DenseMaskAcc> {
3238        self.upper_calls += 1;
3239        let key = (dwa_state, node);
3240        if let Some(cached) = self.upper_memo.get(&key) {
3241            self.upper_hits += 1;
3242            return cached.clone();
3243        }
3244        let indexed = self.dag.nodes[node as usize].clone();
3245        let mut out = match &indexed {
3246            IndexedLeveledGssNode::UpperBranch { .. } => {
3247                let accumulator = self.all_accumulators_upper(node)?;
3248                let accumulator_id = self.accumulator_id(&accumulator);
3249                self.final_for_accumulator(dwa_state, accumulator_id)
3250            }
3251            IndexedLeveledGssNode::Interface { accumulator, lower } => {
3252                let accumulator_id = self.accumulator_id(accumulator);
3253                self.eval_lower(dwa_state, *lower, accumulator_id)
3254            }
3255            IndexedLeveledGssNode::LowerGeneral { .. }
3256            | IndexedLeveledGssNode::LowerSegment { .. } => {
3257                debug_assert!(false, "upper evaluation reached lower node");
3258                None
3259            }
3260        };
3261        if let IndexedLeveledGssNode::UpperBranch { children, .. } = indexed {
3262            for (parser_state, child) in children {
3263                let Some((target, weight)) = self.transition(dwa_state, parser_state) else {
3264                    continue;
3265                };
3266                let child_result = self.eval_upper(target, child);
3267                let child_result = self.intersect_result(child_result, &weight);
3268                Self::merge_result(&mut out, child_result);
3269            }
3270        }
3271        self.upper_memo.insert(key, out.clone());
3272        out
3273    }
3274
3275    fn profile_memo_result(&mut self, result: &Option<DenseMaskAcc>) {
3276        if !indexed_dag_mask_profile_enabled() {
3277            return;
3278        }
3279        let Some(result) = result else {
3280            return;
3281        };
3282        self.memo_result_entries += 1;
3283        for (_, dense) in &result.0 {
3284            let nonzero = dense.iter().filter(|word| **word != 0).count() as u64;
3285            self.memo_dense_words += dense.len() as u64;
3286            self.memo_nonzero_words += nonzero;
3287            self.memo_max_nonzero_words = self.memo_max_nonzero_words.max(nonzero);
3288        }
3289    }
3290
3291    fn single_dense_mask_for_weight(
3292        &self,
3293        weight: &Weight,
3294        tsid: u32,
3295    ) -> IndexedDagDenseMask {
3296        if weight.is_full() {
3297            return IndexedDagDenseMask::Full;
3298        }
3299        let Some(tokens) = weight.token_set_for_tsid_ref(tsid) else {
3300            return IndexedDagDenseMask::Empty;
3301        };
3302        let token_key = Arc::as_ptr(tokens) as usize;
3303        if let Some(dense) = self.precomputed.get(&token_key) {
3304            return Self::single_dense_transition_mask(Arc::clone(dense));
3305        }
3306        let mut dense = vec![0u64; self.constraint.internal_token_dense_words];
3307        DenseMaskAcc::for_each_token_range_word(tokens, dense.len(), |index, mask| {
3308            dense[index] |= mask;
3309        });
3310        Self::single_dense_transition_mask(dense.into())
3311    }
3312
3313    fn single_dense_transition_mask(words: Arc<[u64]>) -> IndexedDagDenseMask {
3314        let Some(start) = words.iter().position(|word| *word != 0) else {
3315            return IndexedDagDenseMask::Empty;
3316        };
3317        let end = words
3318            .iter()
3319            .rposition(|word| *word != 0)
3320            .expect("nonzero start implies nonzero end")
3321            + 1;
3322        IndexedDagDenseMask::Dense { words, start, end }
3323    }
3324
3325    fn single_transition(
3326        &self,
3327        dwa_state: u32,
3328        parser_state: u32,
3329        tsid: u32,
3330    ) -> Option<(u32, &'a IndexedDagDenseMask)> {
3331        let row = self
3332            .constraint
3333            .indexed_dag_dense_transitions
3334            .get(dwa_state as usize)?;
3335        let transition = self
3336            .constraint
3337            .indexed_parser_dwa_transition(row, parser_state)?;
3338        Some((
3339            transition.target,
3340            transition.masks.get(tsid),
3341        ))
3342    }
3343
3344    fn intersect_single_with_dense_mask(
3345        dense: &Arc<[u64]>,
3346        mask: &IndexedDagDenseMask,
3347    ) -> Option<Arc<[u64]>> {
3348        match mask {
3349            IndexedDagDenseMask::Full => Some(Arc::clone(dense)),
3350            IndexedDagDenseMask::Empty => None,
3351            IndexedDagDenseMask::Dense {
3352                words: mask,
3353                start,
3354                end,
3355            } => {
3356                let end = (*end).min(dense.len()).min(mask.len());
3357                if *start >= end {
3358                    return None;
3359                }
3360                if *start != 0 || end != dense.len() {
3361                    let mut out = vec![0u64; end];
3362                    let mut last_nonzero = 0usize;
3363                    for index in *start..end {
3364                        let word = dense[index] & mask[index];
3365                        out[index] = word;
3366                        if word != 0 {
3367                            last_nonzero = index + 1;
3368                        }
3369                    }
3370                    if last_nonzero == 0 {
3371                        return None;
3372                    }
3373                    out.truncate(last_nonzero);
3374                    return Some(out.into());
3375                }
3376                let mut any = false;
3377                let mut out: Option<Vec<u64>> = None;
3378                for index in 0..dense.len() {
3379                    let word = dense[index] & mask[index];
3380                    any |= word != 0;
3381                    if let Some(out) = out.as_mut() {
3382                        out.push(word);
3383                    } else if word != dense[index] {
3384                        let mut changed = Vec::with_capacity(dense.len());
3385                        changed.extend_from_slice(&dense[..index]);
3386                        changed.push(word);
3387                        out = Some(changed);
3388                    }
3389                }
3390                if !any {
3391                    None
3392                } else if let Some(out) = out {
3393                    Some(out.into())
3394                } else {
3395                    Some(Arc::clone(dense))
3396                }
3397            }
3398        }
3399    }
3400
3401    fn merge_single_result(
3402        current: &mut Option<Arc<[u64]>>,
3403        incoming: Option<Arc<[u64]>>,
3404    ) {
3405        let Some(incoming) = incoming else {
3406            return;
3407        };
3408        let Some(existing) = current.as_mut() else {
3409            *current = Some(incoming);
3410            return;
3411        };
3412        if Arc::ptr_eq(existing, &incoming) {
3413            return;
3414        }
3415        if existing.len() == incoming.len() {
3416            let existing = Arc::make_mut(existing);
3417            for (word, incoming_word) in existing.iter_mut().zip(incoming.iter()) {
3418                *word |= *incoming_word;
3419            }
3420            return;
3421        }
3422        let len = existing.len().max(incoming.len());
3423        let mut combined = vec![0u64; len];
3424        for (index, word) in existing.iter().enumerate() {
3425            combined[index] |= *word;
3426        }
3427        for (index, word) in incoming.iter().enumerate() {
3428            combined[index] |= *word;
3429        }
3430        *existing = combined.into();
3431    }
3432
3433    fn merge_single_intersection(
3434        current: &mut Option<Arc<[u64]>>,
3435        incoming: Arc<[u64]>,
3436        mask: &IndexedDagDenseMask,
3437    ) {
3438        match mask {
3439            IndexedDagDenseMask::Full => {
3440                Self::merge_single_result(current, Some(incoming));
3441            }
3442            IndexedDagDenseMask::Empty => {}
3443            IndexedDagDenseMask::Dense {
3444                words: mask,
3445                start,
3446                end,
3447            } => {
3448                let Some(existing) = current.as_mut() else {
3449                    let transition_mask = IndexedDagDenseMask::Dense {
3450                        words: Arc::clone(mask),
3451                        start: *start,
3452                        end: *end,
3453                    };
3454                    *current =
3455                        Self::intersect_single_with_dense_mask(&incoming, &transition_mask);
3456                    return;
3457                };
3458                if Arc::ptr_eq(existing, &incoming) {
3459                    return;
3460                }
3461                let end = (*end).min(incoming.len()).min(mask.len());
3462                if *start >= end {
3463                    return;
3464                }
3465                if existing.len() >= end {
3466                    let existing = Arc::make_mut(existing);
3467                    for index in *start..end {
3468                        existing[index] |= incoming[index] & mask[index];
3469                    }
3470                    return;
3471                }
3472                let len = existing.len().max(end);
3473                let mut combined = vec![0u64; len];
3474                for (index, word) in existing.iter().enumerate() {
3475                    combined[index] = *word;
3476                }
3477                for index in *start..end {
3478                    combined[index] |= incoming[index] & mask[index];
3479                }
3480                *existing = combined.into();
3481            }
3482        }
3483    }
3484
3485    /// Return the parser/GSS transfer mask for one internal tokenizer state,
3486    /// independently of the current seed accumulator.
3487    ///
3488    /// The denotation evaluated below uses only union and intersection with
3489    /// parser-DWA weights. Therefore `E(q, G, a) = a ∩ E(q, G, U)` for every
3490    /// seed accumulator `a` and seed universe `U`. Caching `E(q, G, U)` by
3491    /// `(q, G, tsid)` keeps the result valid when delayed lexer exclusions
3492    /// produce a different `a` at the next model token.
3493    fn final_for_single_transfer(
3494        &self,
3495        dwa_state: u32,
3496        tsid: u32,
3497    ) -> Option<Arc<[u64]>> {
3498        match self
3499            .constraint
3500            .indexed_dag_dense_finals
3501            .get(dwa_state as usize)?
3502            .get(tsid)
3503        {
3504            IndexedDagDenseMask::Full => Some(Arc::clone(&self.constraint.seed_universe_dense)),
3505            IndexedDagDenseMask::Dense { words, .. } => Some(Arc::clone(words)),
3506            IndexedDagDenseMask::Empty => None,
3507        }
3508    }
3509
3510    fn eval_lower_single_transfer(
3511        &mut self,
3512        dwa_state: u32,
3513        node: u32,
3514        tsid: u32,
3515    ) -> Option<Arc<[u64]>> {
3516        self.lower_calls += 1;
3517        let source_slot = self.source_slots[node as usize];
3518        if source_slot == u32::MAX {
3519            debug_assert!(false, "single lower evaluation reached upper node");
3520            return None;
3521        }
3522        let cached = self.runtime.single_sources[source_slot as usize]
3523            .lower
3524            .iter()
3525            .find(|entry| entry.dwa_state == dwa_state && entry.tsid == tsid)
3526            .map(|entry| entry.result.clone());
3527        if let Some(cached) = cached {
3528            self.lower_hits += 1;
3529            return cached;
3530        }
3531        let (empty, child_count) = match &self.dag.nodes[node as usize] {
3532            IndexedLeveledGssNode::LowerGeneral {
3533                empty, children, ..
3534            } => (*empty, children.len()),
3535            IndexedLeveledGssNode::LowerSegment { .. } => {
3536                let out = self.eval_segment_single_transfer(dwa_state, node, 0, tsid);
3537                self.runtime.single_sources[source_slot as usize]
3538                    .lower
3539                    .push(SingleLowerMemoEntry {
3540                        dwa_state,
3541                        tsid,
3542                        result: out.clone(),
3543                    });
3544                return out;
3545            }
3546            _ => unreachable!(),
3547        };
3548        let mut out = (empty || child_count != 0)
3549            .then(|| self.final_for_single_transfer(dwa_state, tsid))
3550            .flatten();
3551        for child_index in 0..child_count {
3552            let (parser_state, child) = match &self.dag.nodes[node as usize] {
3553                IndexedLeveledGssNode::LowerGeneral { children, .. } => {
3554                    children[child_index]
3555                }
3556                _ => unreachable!(),
3557            };
3558            let Some((target, transition_mask)) =
3559                self.single_transition(dwa_state, parser_state, tsid)
3560            else {
3561                continue;
3562            };
3563            if matches!(transition_mask, IndexedDagDenseMask::Empty) {
3564                continue;
3565            }
3566            if let Some(child_result) =
3567                self.eval_lower_single_transfer(target, child, tsid)
3568            {
3569                Self::merge_single_intersection(&mut out, child_result, transition_mask);
3570            }
3571        }
3572        self.runtime.single_sources[source_slot as usize]
3573            .lower
3574            .push(SingleLowerMemoEntry {
3575                dwa_state,
3576                tsid,
3577                result: out.clone(),
3578            });
3579        out
3580    }
3581
3582    fn eval_segment_single_transfer(
3583        &mut self,
3584        dwa_state: u32,
3585        node: u32,
3586        offset: usize,
3587        tsid: u32,
3588    ) -> Option<Arc<[u64]>> {
3589        self.segment_calls += 1;
3590        let source_slot = self.source_slots[node as usize];
3591        if source_slot == u32::MAX {
3592            return None;
3593        }
3594        let cached = self.runtime.single_sources[source_slot as usize]
3595            .segments
3596            .iter()
3597            .find(|entry| {
3598                entry.offset == offset && entry.dwa_state == dwa_state && entry.tsid == tsid
3599            })
3600            .map(|entry| entry.result.clone());
3601        if let Some(cached) = cached {
3602            self.segment_hits += 1;
3603            return cached;
3604        }
3605        let (parser_state, next, has_more) = match &self.dag.nodes[node as usize] {
3606            IndexedLeveledGssNode::LowerSegment {
3607                values,
3608                next,
3609                ..
3610            } => {
3611                let &parser_state =
3612                    values.get(values.len().saturating_sub(1 + offset))?;
3613                (parser_state, *next, offset + 1 < values.len())
3614            }
3615            _ => unreachable!(),
3616        };
3617        let mut out = self.final_for_single_transfer(dwa_state, tsid);
3618        if let Some((target, transition_mask)) =
3619            self.single_transition(dwa_state, parser_state, tsid)
3620            && !matches!(transition_mask, IndexedDagDenseMask::Empty)
3621        {
3622            let child_result = if has_more {
3623                self.eval_segment_single_transfer(
3624                    target,
3625                    node,
3626                    offset + 1,
3627                    tsid,
3628                )
3629            } else {
3630                self.eval_lower_single_transfer(target, next, tsid)
3631            };
3632            if let Some(child_result) = child_result {
3633                Self::merge_single_intersection(&mut out, child_result, transition_mask);
3634            }
3635        }
3636        self.runtime.single_sources[source_slot as usize]
3637            .segments
3638            .push(SingleSegmentMemoEntry {
3639                offset,
3640                dwa_state,
3641                tsid,
3642                result: out.clone(),
3643            });
3644        out
3645    }
3646
3647    fn eval_lower(
3648        &mut self,
3649        dwa_state: u32,
3650        node: u32,
3651        accumulator_id: u32,
3652    ) -> Option<DenseMaskAcc> {
3653        if let Some((tsid, dense)) = self.runtime.accumulators[accumulator_id as usize]
3654            .0
3655            .first()
3656            .filter(|_| self.runtime.accumulators[accumulator_id as usize].0.len() == 1)
3657            .map(|(tsid, dense)| (*tsid, Arc::clone(dense)))
3658        {
3659            let transfer = self.eval_lower_single_transfer(dwa_state, node, tsid)?;
3660            let transfer = Self::single_dense_transition_mask(transfer);
3661            return Self::intersect_single_with_dense_mask(&dense, &transfer)
3662            .and_then(|result| DenseMaskAcc::from_dense_arc(tsid, result));
3663        }
3664        self.lower_calls += 1;
3665        let source_ptr = match &self.dag.nodes[node as usize] {
3666            IndexedLeveledGssNode::LowerGeneral { source, .. }
3667            | IndexedLeveledGssNode::LowerSegment { source, .. } => source.ptr_key(),
3668            IndexedLeveledGssNode::UpperBranch { .. }
3669            | IndexedLeveledGssNode::Interface { .. } => {
3670                debug_assert!(false, "lower evaluation reached upper node");
3671                return None;
3672            }
3673        };
3674        let key = (dwa_state, source_ptr, accumulator_id);
3675        if let Some(cached) = self.runtime.lower_memo.get(&key) {
3676            self.lower_hits += 1;
3677            return cached.clone();
3678        }
3679        let indexed = self.dag.nodes[node as usize].clone();
3680        let source = match &indexed {
3681            IndexedLeveledGssNode::LowerGeneral { source, .. }
3682            | IndexedLeveledGssNode::LowerSegment { source, .. } => source.clone(),
3683            IndexedLeveledGssNode::UpperBranch { .. }
3684            | IndexedLeveledGssNode::Interface { .. } => unreachable!(),
3685        };
3686        let out = match indexed {
3687            IndexedLeveledGssNode::LowerGeneral {
3688                empty, children, ..
3689            } => {
3690                let has_paths = empty || !children.is_empty();
3691                let mut out = has_paths
3692                    .then(|| self.final_for_accumulator(dwa_state, accumulator_id))
3693                    .flatten();
3694                for (parser_state, child) in children {
3695                    let Some((target, weight)) = self.transition(dwa_state, parser_state) else {
3696                        continue;
3697                    };
3698                    let child_result = self.eval_lower(target, child, accumulator_id);
3699                    let child_result = self.intersect_result(child_result, &weight);
3700                    Self::merge_result(&mut out, child_result);
3701                }
3702                out
3703            }
3704            IndexedLeveledGssNode::LowerSegment { .. } => {
3705                self.eval_segment(dwa_state, node, 0, accumulator_id)
3706            }
3707            IndexedLeveledGssNode::UpperBranch { .. }
3708            | IndexedLeveledGssNode::Interface { .. } => unreachable!(),
3709        };
3710        self.profile_memo_result(&out);
3711        self.runtime
3712            .lower_sources
3713            .entry(source_ptr)
3714            .or_insert(source);
3715        self.runtime.lower_memo.insert(key, out.clone());
3716        out
3717    }
3718
3719    fn eval_segment(
3720        &mut self,
3721        dwa_state: u32,
3722        node: u32,
3723        offset: usize,
3724        accumulator_id: u32,
3725    ) -> Option<DenseMaskAcc> {
3726        self.segment_calls += 1;
3727        let source_ptr = match &self.dag.nodes[node as usize] {
3728            IndexedLeveledGssNode::LowerSegment { source, .. } => source.ptr_key(),
3729            _ => {
3730                debug_assert!(false, "segment evaluation reached non-segment node");
3731                return None;
3732            }
3733        };
3734        let key = (source_ptr, offset, dwa_state, accumulator_id);
3735        if let Some(cached) = self.runtime.segment_memo.get(&key) {
3736            self.segment_hits += 1;
3737            return cached.clone();
3738        }
3739        let IndexedLeveledGssNode::LowerSegment {
3740            source,
3741            values,
3742            next,
3743        } = self.dag.nodes[node as usize].clone()
3744        else {
3745            unreachable!("segment source changed during evaluation");
3746        };
3747        let mut out = self.final_for_accumulator(dwa_state, accumulator_id);
3748        if let Some(&parser_state) = values.get(values.len().saturating_sub(1 + offset))
3749            && let Some((target, weight)) = self.transition(dwa_state, parser_state)
3750        {
3751            let child_result = if offset + 1 < values.len() {
3752                self.eval_segment(target, node, offset + 1, accumulator_id)
3753            } else {
3754                self.eval_lower(target, next, accumulator_id)
3755            };
3756            let child_result = self.intersect_result(child_result, &weight);
3757            Self::merge_result(&mut out, child_result);
3758        }
3759        self.profile_memo_result(&out);
3760        self.runtime
3761            .lower_sources
3762            .entry(source_ptr)
3763            .or_insert(source);
3764        self.runtime.segment_memo.insert(key, out.clone());
3765        out
3766    }
3767}
3768
3769fn enqueue_gss(queue: &mut MaskQueue, target: u32, gss: DenseMaskGSS) {
3770    queue.enqueue(target, gss);
3771}
3772
3773fn dense_gss_transition_key(
3774    gss: &DenseMaskGSS,
3775    weight: &Weight,
3776) -> Option<DenseGssTransitionKey> {
3777    let lower = gss.single_interface_lower_id()?;
3778    let mut entries = SmallVec::new();
3779    gss.for_each_acc(|acc| {
3780        for (tsid, dense) in &acc.0 {
3781            let token_set = weight
3782                .token_set_for_tsid_ref(*tsid)
3783                .map(|set| Arc::as_ptr(set) as usize)
3784                .unwrap_or(0);
3785            entries.push((*tsid, dense.as_ptr() as usize, dense.len(), token_set));
3786        }
3787    });
3788    entries.sort_unstable();
3789    Some(DenseGssTransitionKey { lower, entries })
3790}
3791
3792fn enqueue_weighted_transition(
3793    queue: &mut MaskQueue,
3794    popped: &DenseMaskGSS,
3795    target: u32,
3796    weight: RuntimeWeightRef<'_>,
3797    precomputed: &DenseTokenMaskCache,
3798    transition_gss_cache: &mut FxHashMap<DenseGssTransitionKey, DenseMaskGSS>,
3799    transition_intersection_cache: &mut DenseTokenSetIntersectionSmallCache,
3800    profile: &mut Option<MaskInnerProfileStats>,
3801) {
3802    if weight.is_full() {
3803        enqueue_gss(queue, target, popped.clone());
3804        return;
3805    }
3806
3807    let profile_enabled = profile.is_some();
3808    let apply_start = if profile_enabled {
3809        Some(Instant::now())
3810    } else {
3811        None
3812    };
3813    let mut intersect_ns = 0u64;
3814    let cache_key = None;
3815    if let Some(key) = cache_key.as_ref()
3816        && let Some(cached) = transition_gss_cache.get(key) {
3817            if let (Some(profile), Some(start)) = (profile.as_mut(), apply_start) {
3818                let apply_ns = elapsed_ns(start);
3819                profile.transition_apply_ns += apply_ns;
3820                profile.transition_apply_gss_ns += apply_ns;
3821            }
3822            enqueue_gss(queue, target, cached.clone());
3823            return;
3824        }
3825
3826    let pruned = popped.apply_and_prune_no_promote(|allowed| {
3827        let intersect_start = if profile_enabled {
3828            Some(Instant::now())
3829        } else {
3830            None
3831        };
3832        let intersected = allowed.intersect_with_runtime_weight_small_cached(
3833            weight,
3834            precomputed,
3835            transition_intersection_cache,
3836        );
3837        if let Some(start) = intersect_start {
3838            intersect_ns += elapsed_ns(start);
3839        }
3840        intersected
3841    });
3842    if let Some(key) = cache_key {
3843        transition_gss_cache.insert(key, pruned.clone());
3844    }
3845    if let (Some(profile), Some(start)) = (profile.as_mut(), apply_start) {
3846        let apply_ns = elapsed_ns(start);
3847        profile.transition_apply_ns += apply_ns;
3848        profile.transition_apply_intersect_ns += intersect_ns;
3849        profile.transition_apply_gss_ns += apply_ns.saturating_sub(intersect_ns);
3850    }
3851
3852    enqueue_gss(queue, target, pruned);
3853}
3854
3855fn enqueue_parser_state_transition(
3856    constraint: &Constraint,
3857    queue: &mut MaskQueue,
3858    dwa_state: u32,
3859    parser_state: u32,
3860    popped: &DenseMaskGSS,
3861    precomputed: &DenseTokenMaskCache,
3862    transition_gss_cache: &mut FxHashMap<DenseGssTransitionKey, DenseMaskGSS>,
3863    transition_intersection_cache: &mut DenseTokenSetIntersectionSmallCache,
3864    profile: &mut Option<MaskInnerProfileStats>,
3865) {
3866    let lookup_start = if profile.is_some() {
3867        Some(Instant::now())
3868    } else {
3869        None
3870    };
3871    let Some((target, weight)) = constraint
3872        .runtime_parser_dwa_transition(dwa_state, parser_state)
3873    else {
3874        if let (Some(profile), Some(start)) = (profile.as_mut(), lookup_start) {
3875            profile.transition_lookup_ns += elapsed_ns(start);
3876        }
3877        return;
3878    };
3879    if let (Some(profile), Some(start)) = (profile.as_mut(), lookup_start) {
3880        profile.transition_lookup_ns += elapsed_ns(start);
3881    }
3882
3883    queue.record_parser_dwa_transition_enqueue();
3884    enqueue_weighted_transition(
3885        queue,
3886        popped,
3887        target,
3888        weight,
3889        precomputed,
3890        transition_gss_cache,
3891        transition_intersection_cache,
3892        profile,
3893    );
3894}
3895
3896/// One exact weighted-GSS queue traversal for ordinary and boundary parser
3897/// DWAs. Namespace selection and weight representation are supplied outside
3898/// the traversal; queue scheduling, decomposition and profiling are shared.
3899/// Closures are monomorphised, so ordinary lookup/intersection fast paths keep
3900/// their existing implementation rather than acquiring virtual dispatch.
3901/// Inline the executor into each provider so extracting the shared loop does
3902/// not leave the ordinary hot path behind an additional closure-call boundary.
3903#[inline(always)]
3904fn walk_static_dwa_gss_queue<W>(
3905    queue: &mut MaskQueue,
3906    profile: &mut Option<MaskInnerProfileStats>,
3907    mut final_weight: impl FnMut(u32) -> Option<W>,
3908    mut transition: impl FnMut(u32, u32) -> Option<(u32, W)>,
3909    mut accumulate: impl FnMut(W, &DenseMaskGSS),
3910    mut enqueue: impl FnMut(&mut MaskQueue, u32, W, &DenseMaskGSS, &mut Option<MaskInnerProfileStats>),
3911) {
3912    loop {
3913        let popped = queue.pop_next();
3914        if let Some(profile) = profile.as_mut() {
3915            profile.queue_pop_ns = queue.debug_stats().pop_total_ns;
3916        }
3917        let Some((wa_state, gss)) = popped else { break; };
3918        if let Some(weight) = final_weight(wa_state) {
3919            let started = profile.as_ref().map(|_| Instant::now());
3920            accumulate(weight, &gss);
3921            if let (Some(profile), Some(started)) = (profile.as_mut(), started) {
3922                profile.token_accumulation_ns += elapsed_ns(started);
3923            }
3924        }
3925        let decompose_started = profile.as_ref().map(|_| Instant::now());
3926        gss.for_each_decomposed(|parser_state, popped| {
3927            let callback_started = profile.as_ref().map(|_| Instant::now());
3928            queue.record_loop_decompose_callback();
3929            let lookup_started = profile.as_ref().map(|_| Instant::now());
3930            let edge = transition(wa_state, parser_state);
3931            if let (Some(profile), Some(started)) = (profile.as_mut(), lookup_started) {
3932                profile.transition_lookup_ns += elapsed_ns(started);
3933            }
3934            if let Some((target, weight)) = edge {
3935                queue.record_parser_dwa_transition_enqueue();
3936                enqueue(queue, target, weight, &popped, profile);
3937            }
3938            if let (Some(profile), Some(started)) = (profile.as_mut(), callback_started) {
3939                profile.loop_decompose_callback_ns += elapsed_ns(started);
3940            }
3941        });
3942        if let (Some(profile), Some(started)) = (profile.as_mut(), decompose_started) {
3943            profile.loop_decompose_total_ns += elapsed_ns(started);
3944        }
3945    }
3946}
3947
3948fn boundary_queue_seed(
3949    stacks: &LeveledGSS<u32, ()>,
3950    seed: &DenseMaskAcc,
3951    top_live: &impl Fn(Option<u32>) -> bool,
3952) -> DenseMaskGSS {
3953    let dense = stacks.apply(|_| seed.clone());
3954    let mut filtered = if top_live(None) { dense.isolate(None) } else { DenseMaskGSS::empty() };
3955    dense.for_each_decomposed(|top, popped| {
3956        if top_live(Some(top)) {
3957            filtered = filtered.merge(&popped.push(top));
3958        }
3959    });
3960    filtered
3961}
3962
3963fn merge_boundary_dense_result(output: &mut Option<DenseMaskAcc>, incoming: Option<DenseMaskAcc>) {
3964    if let Some(incoming) = incoming {
3965        if let Some(output) = output.as_mut() { output.merge_in_place(&incoming); }
3966        else { *output = Some(incoming); }
3967    }
3968}
3969
3970/// Provider adapter for private, materialized boundary-DWA weights. The graph
3971/// traversal and dense intersection/cache machinery are the ordinary engine's.
3972fn boundary_weight_mask_via_shared_queue(
3973    dwa: &crate::automata::weighted_u32::dwa::DWA,
3974    tsids: &[u32],
3975    token_count: usize,
3976    stacks: &LeveledGSS<u32, ()>,
3977    top_live: &impl Fn(Option<u32>) -> bool,
3978) -> Option<DenseMaskAcc> {
3979    if token_count == 0 || tsids.is_empty() { return None; }
3980    let mut full = vec![u64::MAX; token_count.div_ceil(64)];
3981    if !token_count.is_multiple_of(64) { *full.last_mut().unwrap() = (1u64 << (token_count % 64)) - 1; }
3982    let seed = DenseMaskAcc::from_dense_arc_for_tsids(tsids, Arc::from(full))?;
3983    let mut queue = MaskQueue::new();
3984    queue.enqueue(dwa.start_state(), boundary_queue_seed(stacks, &seed, top_live));
3985    let precomputed = DenseTokenMaskCache::default();
3986    let mut transition_cache = FxHashMap::default();
3987    let mut intersection_cache = DenseTokenSetIntersectionSmallCache::new();
3988    let mut output = None;
3989    walk_static_dwa_gss_queue(
3990        &mut queue,
3991        &mut None,
3992        |state| dwa.states().get(state as usize).and_then(|row| row.final_weight.as_ref())
3993            .map(RuntimeWeightRef::Materialized),
3994        |state, parser| {
3995            let row = &dwa.states().get(state as usize)?.transitions;
3996            row.get(&encode_positive_label(parser)).or_else(|| row.get(&DEFAULT_LABEL))
3997                .map(|(target, weight)| (*target, RuntimeWeightRef::Materialized(weight)))
3998        },
3999        |weight, gss| {
4000            gss.for_each_acc(|acc| {
4001                merge_boundary_dense_result(&mut output,
4002                    acc.intersect_with_runtime_weight_reuse(weight, &precomputed));
4003            });
4004        },
4005        |queue, target, weight, popped, profile| {
4006            enqueue_weighted_transition(queue, popped, target, weight, &precomputed,
4007                &mut transition_cache, &mut intersection_cache, profile);
4008        },
4009    );
4010    output
4011}
4012
4013/// The small boundary representation supplies one-word intersections to the
4014/// same traversal. It does not have an independent GSS/DWA walk.
4015fn boundary_mask64_via_shared_queue(
4016    dwa: &crate::compiler::stages::parser_dwa::SmallBoundaryDwa,
4017    tsid: u32,
4018    stacks: &LeveledGSS<u32, ()>,
4019    top_live: &impl Fn(Option<u32>) -> bool,
4020) -> Option<DenseMaskAcc> {
4021    if tsid >= dwa.tsid_count as u32 { return None; }
4022    let full = dwa.all_token_mask();
4023    let seed = DenseMaskAcc::from_dense(tsid, vec![full])?;
4024    let mut queue = MaskQueue::new();
4025    queue.enqueue(dwa.start_state(), boundary_queue_seed(stacks, &seed, top_live));
4026    let intersect = |acc: &DenseMaskAcc, mask: u64| {
4027        debug_assert_eq!(acc.0.len(), 1);
4028        let (tsid, words) = acc.0.first()?;
4029        debug_assert_eq!(words.len(), 1);
4030        DenseMaskAcc::from_dense(*tsid, vec![words[0] & mask])
4031    };
4032    let mut output = None;
4033    walk_static_dwa_gss_queue(
4034        &mut queue,
4035        &mut None,
4036        |state| {
4037            let weight = dwa.states.get(state as usize)?.final_weight;
4038            (weight != 0).then(|| dwa.weight_mask(weight, tsid))
4039        },
4040        |state, parser| {
4041            let row = &dwa.states.get(state as usize)?.transitions;
4042            let label = encode_positive_label(parser);
4043            row.iter().find(|(key, _, _)| *key == label)
4044                .or_else(|| row.iter().find(|(key, _, _)| *key == DEFAULT_LABEL))
4045                .map(|&(_, target, weight)| (target, dwa.weight_mask(weight, tsid)))
4046        },
4047        |mask, gss| {
4048            gss.for_each_acc(|acc| merge_boundary_dense_result(&mut output, intersect(acc, mask)));
4049        },
4050        |queue, target, mask, popped, _profile| {
4051            if mask == full { queue.enqueue(target, popped.clone()); }
4052            else if mask != 0 { queue.enqueue(target, popped.apply_and_prune(|acc| intersect(acc, mask))); }
4053        },
4054    );
4055    output
4056}
4057
4058impl ConstraintState {
4059    fn or_segmented_component_mask(&self, output: &mut [u32], component_mask: &[u32]) {
4060        // Retained components can carry private linker sentinel IDs (and other
4061        // component-local specials) that are deliberately absent from the
4062        // finished outer constraint.  Their masks are expressed in original
4063        // token-ID space, so never OR those private IDs straight through into
4064        // the caller-visible mask.  Intersect with the outer constraint's
4065        // actual token universe while copying set bits.
4066        // Most model vocabularies have exactly the byte IDs 0..N. Prove that
4067        // from the existing immutable index: N distinct nonnegative IDs with
4068        // maximum N-1 leave no holes. No vocabulary scan, derived table or
4069        // composition-build work is needed. Copy this proven prefix with the
4070        // same word-wise OR used by the ordinary mask path, and retain exact
4071        // pointwise membership for sparse IDs / private-special-token tails.
4072        let (byte_count, max_byte_id) = self.constraint.packed_token_bytes.as_ref()
4073            .map(|packed| (packed.len(), packed.max_token_id()))
4074            .unwrap_or_else(|| (
4075                self.constraint.token_bytes.len(),
4076                self.constraint.token_bytes.last_key_value().map(|(&id, _)| id),
4077            ));
4078        let dense_byte_count = if byte_count != 0
4079            && max_byte_id.is_some_and(|id| u64::from(id) + 1 == byte_count as u64)
4080        { byte_count } else { 0 };
4081        let full_words = (dense_byte_count / 32).min(output.len()).min(component_mask.len());
4082        for (target, &source) in output[..full_words].iter_mut().zip(&component_mask[..full_words]) {
4083            *target |= source;
4084        }
4085        for (word_index, (&source_word, target_word)) in component_mask
4086            .iter()
4087            .zip(output.iter_mut())
4088            .enumerate()
4089            .skip(full_words)
4090        {
4091            let known_prefix = if word_index == dense_byte_count / 32 && dense_byte_count % 32 != 0 {
4092                (1u32 << (dense_byte_count % 32)) - 1
4093            } else { 0 };
4094            *target_word |= source_word & known_prefix;
4095            let mut remaining = source_word & !*target_word;
4096            while remaining != 0 {
4097                let bit = remaining.trailing_zeros();
4098                let token_id = word_index as u32 * 32 + bit;
4099                if self.knows_token_id(token_id) {
4100                    *target_word |= 1u32 << bit;
4101                }
4102                remaining &= remaining - 1;
4103            }
4104        }
4105    }
4106
4107    /// Project one visible outer tokenizer state into every raw tokenizer
4108    /// state of `component` that it represents.
4109    ///
4110    /// Before runtime-product compression the composed lexer is a literal
4111    /// disjoint union, so this is just `global = component_offset + local`
4112    /// (with union state zero acting as the shared reset dispatcher). If the
4113    /// composed constraint later installs a deterministic runtime product, a
4114    /// visible product state denotes a subset of those old union states; lift
4115    /// that retained source relation back through the same offsets rather than
4116    /// pretending the product state itself is in component coordinates.
4117    fn segmented_local_tokenizer_states(
4118        &self,
4119        component_index: usize,
4120        component: &crate::runtime::SegmentedParserComponent,
4121        global_state: u32,
4122    ) -> SmallVec<[u32; 8]> {
4123        if self.constraint.uses_compact_segmented_parser_runtime() {
4124            return self
4125                .constraint
4126                .recursive_tokenizer_state_for_component(component_index, global_state)
4127                .into_iter()
4128                .collect();
4129        }
4130        let mut locals = SmallVec::<[u32; 8]>::new();
4131        let component_reset = component.constraint.runtime_commit_initial_state();
4132        let component_offset = component.tokenizer_state_offset;
4133        let component_states = component.constraint.tokenizer.num_states();
4134
4135        let mut add_source_union_state = |source_state: u32| {
4136            // Source-union state zero is the shared reset dispatcher rather
4137            // than one component's physical state. In a component projection
4138            // it denotes that component's authoritative commit reset.
4139            if source_state == 0 {
4140                locals.push(component_reset);
4141                return;
4142            }
4143            let Some(local) = source_state.checked_sub(component_offset) else {
4144                return;
4145            };
4146            if local < component_states {
4147                locals.push(local);
4148            }
4149        };
4150
4151        if global_state == self.constraint.runtime_commit_initial_state() {
4152            locals.push(component_reset);
4153        } else if let Some(source_offset) = self.constraint.runtime_source_state_offset() {
4154            if global_state >= source_offset {
4155                add_source_union_state(global_state - source_offset);
4156            } else if let Some(source_states) =
4157                self.constraint.runtime_product_source_states(global_state)
4158            {
4159                for &source_state in source_states {
4160                    add_source_union_state(source_state);
4161                }
4162            }
4163        } else {
4164            add_source_union_state(global_state);
4165        }
4166
4167        locals.sort_unstable();
4168        locals.dedup();
4169        locals
4170    }
4171
4172    #[inline]
4173    fn segmented_local_parser_state(
4174        &self,
4175        component_index: usize,
4176        component: &crate::runtime::SegmentedParserComponent,
4177        parser_state: u32,
4178    ) -> Option<u32> {
4179        if self.constraint.uses_compact_segmented_parser_runtime() {
4180            return self
4181                .constraint
4182                .compact_segmented_parser_local_state(component_index, parser_state);
4183        }
4184        component
4185            .global_to_local_parser_state
4186            .get(parser_state as usize)
4187            .copied()
4188            .filter(|&local| local != u32::MAX)
4189    }
4190
4191    #[inline]
4192    fn segmented_component_for_parser_state(
4193        &self,
4194        dispatch: &[u32],
4195        parser_state: u32,
4196    ) -> Option<usize> {
4197        if self.constraint.uses_compact_segmented_parser_runtime() {
4198            return self
4199                .constraint
4200                .compact_segmented_parser_component(parser_state)
4201                .map(|(component, _)| component);
4202        }
4203        let component = dispatch.get(parser_state as usize).copied()?;
4204        (component != u32::MAX).then_some(component as usize)
4205    }
4206
4207    fn segmented_local_disallowed(
4208        &self,
4209        component_index: usize,
4210        component: &crate::runtime::SegmentedParserComponent,
4211        source: &TerminalsDisallowed,
4212    ) -> TerminalsDisallowed {
4213        let terminal_start = component.terminal_offset;
4214        let terminal_end = terminal_start.saturating_add(component.constraint.parser_terminal_count());
4215        let mut result = TerminalsDisallowed::new();
4216        for (global_tokenizer_state, terminals) in source.iter() {
4217            let local_tokenizer_states = self.segmented_local_tokenizer_states(
4218                component_index,
4219                component,
4220                *global_tokenizer_state,
4221            );
4222            for local_tokenizer_state in local_tokenizer_states {
4223                for &terminal in terminals.iter() {
4224                    if self.constraint.uses_compact_segmented_parser_runtime()
4225                        && let Some(local_terminal) = self
4226                            .constraint
4227                            .recursive_terminal_for_component(component_index, terminal)
4228                        {
4229                            result = result.with_insert(local_tokenizer_state, local_terminal);
4230                            continue;
4231                        }
4232                    if terminal_start <= terminal && terminal < terminal_end {
4233                        result = result.with_insert(
4234                            local_tokenizer_state,
4235                            terminal - terminal_start,
4236                        );
4237                    }
4238                    for &(alias, local_terminal) in &component.global_terminal_aliases {
4239                        if alias == terminal {
4240                            result = result.with_insert(local_tokenizer_state, local_terminal);
4241                        }
4242                    }
4243                }
4244            }
4245        }
4246        result
4247    }
4248
4249    fn try_fill_mask_segmented_deterministic_union_direct(&self, buf: &mut [u32]) -> bool {
4250        fn accepted_for_stack(
4251            component: &crate::runtime::SegmentedParserComponent,
4252            top_first: &[u32],
4253        ) -> Weight {
4254            let constraint = component.constraint.as_ref();
4255            let dwa = &constraint.parser_dwa;
4256            let mut ops = crate::ds::weight::ScopedWeightOpCache::default();
4257            let mut state_id = dwa.start_state();
4258            let mut path_weight = Weight::all();
4259            let mut accepted = Weight::empty();
4260            let accumulate = |state_id: u32,
4261                              path_weight: &Weight,
4262                              accepted: &mut Weight,
4263                              ops: &mut crate::ds::weight::ScopedWeightOpCache| {
4264                if let Some(final_weight) = dwa
4265                    .states()
4266                    .get(state_id as usize)
4267                    .and_then(|state| state.final_weight.as_ref())
4268                {
4269                    let contribution = ops.intersection(path_weight, final_weight);
4270                    if !contribution.is_empty() {
4271                        *accepted = ops.union(accepted, &contribution);
4272                    }
4273                }
4274            };
4275            accumulate(state_id, &path_weight, &mut accepted, &mut ops);
4276            for &parser_state in top_first {
4277                let Some(state) = dwa.states().get(state_id as usize) else {
4278                    break;
4279                };
4280                let positive = encode_positive_label(parser_state);
4281                let transition = state
4282                    .transitions
4283                    .get(&positive)
4284                    .or_else(|| {
4285                        constraint
4286                            .parser_state_domain_label(parser_state)
4287                            .and_then(|label| state.transitions.get(&label))
4288                    })
4289                    .or_else(|| state.transitions.get(&DEFAULT_LABEL));
4290                let Some((target, edge_weight)) = transition else {
4291                    break;
4292                };
4293                path_weight = ops.intersection(&path_weight, edge_weight);
4294                if path_weight.is_empty() {
4295                    break;
4296                }
4297                state_id = *target;
4298                accumulate(state_id, &path_weight, &mut accepted, &mut ops);
4299            }
4300            accepted
4301        }
4302
4303        fn dense_contains(acc: &DenseMaskAcc, token: u32) -> bool {
4304            let word = token as usize / 64;
4305            let bit = token % 64;
4306            acc.0.iter().any(|(_, dense)| {
4307                dense.get(word)
4308                    .is_some_and(|word_value| (*word_value & (1u64 << bit)) != 0)
4309            })
4310        }
4311
4312        fn or_component_weight(
4313            outer: &ConstraintState,
4314            component_index: usize,
4315            component: &crate::runtime::SegmentedParserComponent,
4316            global_tokenizer_state: u32,
4317            accepted: &Weight,
4318            allowed: &DenseMaskAcc,
4319            root_disallow: bool,
4320            buf: &mut [u32],
4321        ) -> bool {
4322            let local_tokenizer_states = outer.segmented_local_tokenizer_states(
4323                component_index,
4324                component,
4325                global_tokenizer_state,
4326            );
4327            if local_tokenizer_states.is_empty() {
4328                return true;
4329            }
4330            let source = component.constraint.as_ref();
4331            let blocked = root_disallow
4332                .then_some(component.root_disallowed_terminal)
4333                .flatten()
4334                .and_then(|terminal| source.possible_matches.get(&terminal));
4335            for local_tokenizer_state in local_tokenizer_states {
4336                for &tsid in source.internal_tsids_for_state(local_tokenizer_state) {
4337                    let accepted_tokens = if accepted.is_full() {
4338                        source.internal_token_universe()
4339                    } else {
4340                        accepted.tokens_for_tsid(tsid)
4341                    };
4342                    if accepted_tokens.is_empty() {
4343                        continue;
4344                    }
4345                    let blocked_tokens = blocked.map(|weight| {
4346                        if weight.is_full() {
4347                            source.internal_token_universe()
4348                        } else {
4349                            weight.tokens_for_tsid(tsid)
4350                        }
4351                    });
4352                    for internal_token in accepted_tokens.iter() {
4353                        if blocked_tokens
4354                            .as_ref()
4355                            .is_some_and(|tokens| tokens.contains(internal_token))
4356                        {
4357                            continue;
4358                        }
4359                        if source.internal_token_to_tokens.is_empty() {
4360                            let original = internal_token;
4361                            let outer_internal = outer
4362                                .constraint
4363                                .original_token_internal_at(original)
4364                                .unwrap_or(u32::MAX);
4365                            if outer_internal != u32::MAX && dense_contains(allowed, outer_internal) {
4366                                set_original_mask_bit(buf, original);
4367                            }
4368                        } else if let Some(originals) =
4369                            source.internal_token_to_tokens.get(internal_token as usize)
4370                        {
4371                            for &original in originals {
4372                                let outer_internal = outer
4373                                    .constraint
4374                                    .original_token_internal_at(original)
4375                                    .unwrap_or(u32::MAX);
4376                                if outer_internal != u32::MAX
4377                                    && dense_contains(allowed, outer_internal)
4378                                {
4379                                    set_original_mask_bit(buf, original);
4380                                }
4381                            }
4382                        }
4383                    }
4384                }
4385            }
4386            true
4387        }
4388
4389        let Some(overlay) = self.constraint.static_dynamic_overlay.as_ref() else {
4390            return false;
4391        };
4392        let dispatch = &overlay.segmented_component_union_root_dispatch;
4393        if overlay.segmented_parser_components.is_empty()
4394            || (!self.constraint.uses_compact_segmented_parser_runtime() && dispatch.is_empty())
4395        {
4396            return false;
4397        }
4398        if overlay.segmented_static_baseline {
4399            self.fill_mask_uncached(buf);
4400        } else {
4401            buf.fill(0);
4402        }
4403        for (&global_tokenizer_state, gss) in self.state.iter() {
4404            let mut complete = true;
4405            let traversal_complete = gss.for_each_stack_top_first_bounded(128, |top_first, acc| {
4406                let Some(allowed) =
4407                    self.terminals_disallowed_to_dense_acc(acc, global_tokenizer_state)
4408                else {
4409                    complete = false;
4410                    return;
4411                };
4412                // Synthetic root final: every component start final contributes.
4413                for (component_index, component) in
4414                    overlay.segmented_parser_components.iter().enumerate()
4415                {
4416                    let accepted = accepted_for_stack(component, &[]);
4417                    if !or_component_weight(
4418                        self,
4419                        component_index,
4420                        component,
4421                        global_tokenizer_state,
4422                        &accepted,
4423                        &allowed,
4424                        true,
4425                        buf,
4426                    ) {
4427                        complete = false;
4428                        return;
4429                    }
4430                }
4431                let Some(&global_top) = top_first.first() else {
4432                    return;
4433                };
4434                let Some(component_index) =
4435                    self.segmented_component_for_parser_state(dispatch, global_top)
4436                else {
4437                    return;
4438                };
4439                let Some(component) = overlay
4440                    .segmented_parser_components
4441                    .get(component_index)
4442                else {
4443                    complete = false;
4444                    return;
4445                };
4446                let mut local_top_first = SmallVec::<[u32; 64]>::new();
4447                for &global_parser_state in top_first {
4448                    let Some(local) = self.segmented_local_parser_state(
4449                        component_index,
4450                        component,
4451                        global_parser_state,
4452                    ) else {
4453                        break;
4454                    };
4455                    local_top_first.push(local);
4456                }
4457                if local_top_first.is_empty() {
4458                    return;
4459                }
4460                let accepted = accepted_for_stack(component, &local_top_first);
4461                if !or_component_weight(
4462                    self,
4463                    component_index,
4464                    component,
4465                    global_tokenizer_state,
4466                    &accepted,
4467                    &allowed,
4468                    false,
4469                    buf,
4470                ) {
4471                    complete = false;
4472                }
4473            });
4474            if !traversal_complete || !complete {
4475                return false;
4476            }
4477        }
4478        if !self.or_segmented_boundary_shards_mask(overlay, buf) {
4479            return false;
4480        }
4481        true
4482    }
4483
4484    /// Evaluate deterministic component A. In the recursive parser runtime,
4485    /// immediate-wrapper state intervals select the component directly. Legacy
4486    /// materialized-coordinate runtimes use `segmented_component_union_root_dispatch`
4487    /// for the same selection. Root final weights are the union of every
4488    /// component start final, so we also project an empty stack into each
4489    /// component coordinate for the same branch accumulator.
4490    fn try_fill_mask_segmented_deterministic_union(&self, buf: &mut [u32]) -> bool {
4491        if !self.constraint.uses_compact_segmented_parser_runtime()
4492            && crate::env::var_os("GLRMASK_EXPERIMENT_SEGMENTED_DIRECT_COMPONENT_DWA_MASK").is_some()
4493        {
4494            return self.try_fill_mask_segmented_deterministic_union_direct(buf);
4495        }
4496        let profile = crate::env::var_os("GLRMASK_PROFILE_SEGMENTED_MASK").is_some();
4497        let total_started_at = profile.then(Instant::now);
4498        let Some(overlay) = self.constraint.static_dynamic_overlay.as_ref() else {
4499            return false;
4500        };
4501        let dispatch = &overlay.segmented_component_union_root_dispatch;
4502        if overlay.segmented_parser_components.is_empty()
4503            || (!self.constraint.uses_compact_segmented_parser_runtime() && dispatch.is_empty())
4504        {
4505            return false;
4506        }
4507
4508        let mut projected_states = SmallVec::<[ParserStateMap; 4]>::new();
4509        projected_states.resize_with(
4510            overlay.segmented_parser_components.len(),
4511            ParserStateMap::default,
4512        );
4513
4514        for (&global_tokenizer_state, gss) in self.state.iter() {
4515            // A control-closed recursive frontier can represent exponentially
4516            // many valid stacks. Project its shared graph instead of declaring
4517            // a static-mask failure after enumerating 128 concrete paths.
4518            if self.constraint.uses_compact_segmented_parser_runtime() && !gss.is_single_path() {
4519                for (component_index, component) in overlay.segmented_parser_components.iter().enumerate() {
4520                    let local_tokenizer_states = self.segmented_local_tokenizer_states(
4521                        component_index, component, global_tokenizer_state);
4522                    if local_tokenizer_states.is_empty() { continue; }
4523                    let projected = gss.map_nonempty_top_prefixes(|&global|
4524                        self.segmented_local_parser_state(component_index, component, global));
4525                    if projected.is_empty() { continue; }
4526                    let projected = projected.apply_and_prune(|acc|
4527                        Some(self.segmented_local_disallowed(component_index, component, acc)));
4528                    for local_state in local_tokenizer_states {
4529                        projected_states[component_index].merge_insert(local_state, projected.clone());
4530                    }
4531                }
4532                continue;
4533            }
4534            let complete = gss.for_each_stack_top_first_bounded(128, |top_first, acc| {
4535                // The old materialized segmented union had one synthetic root
4536                // whose final language was the union of every component start
4537                // final.  The recursive provider coordinate has no such root:
4538                // state 0 is the real root leaf state, and CALL is the only way
4539                // to make a child active.  Seeding all component roots here in
4540                // the recursive runtime would therefore leak a child's scoped
4541                // ignore into its parent before the CALL.
4542                if !self.constraint.uses_compact_segmented_parser_runtime() {
4543                    for (component_index, component) in
4544                        overlay.segmented_parser_components.iter().enumerate()
4545                    {
4546                        let local_tokenizer_states = self
4547                            .segmented_local_tokenizer_states(
4548                                component_index,
4549                                component,
4550                                global_tokenizer_state,
4551                            );
4552                        if local_tokenizer_states.is_empty() {
4553                            continue;
4554                        }
4555                        let local_disallowed =
4556                            self.segmented_local_disallowed(component_index, component, acc);
4557                        for local_tokenizer_state in local_tokenizer_states {
4558                            let mut branch_disallowed = local_disallowed.clone();
4559                            if let Some(terminal) = component.root_disallowed_terminal {
4560                                branch_disallowed = branch_disallowed.with_insert(
4561                                    local_tokenizer_state,
4562                                    terminal,
4563                                );
4564                            }
4565                            let root_gss =
4566                                ParserGSS::from_single_stack(Vec::new(), branch_disallowed);
4567                            projected_states[component_index].merge_insert(
4568                                local_tokenizer_state,
4569                                root_gss,
4570                            );
4571                        }
4572                    }
4573                }
4574
4575                let Some(&global_top) = top_first.first() else {
4576                    return;
4577                };
4578                let Some(component_index) =
4579                    self.segmented_component_for_parser_state(dispatch, global_top)
4580                else {
4581                    return;
4582                };
4583                let Some(component) = overlay
4584                    .segmented_parser_components
4585                    .get(component_index)
4586                else {
4587                    return;
4588                };
4589                let local_tokenizer_states = self.segmented_local_tokenizer_states(
4590                    component_index,
4591                    component,
4592                    global_tokenizer_state,
4593                );
4594                if local_tokenizer_states.is_empty() {
4595                    return;
4596                }
4597
4598                let mut local_top_first = SmallVec::<[u32; 64]>::new();
4599                for &global_parser_state in top_first {
4600                    let Some(local) = self.segmented_local_parser_state(
4601                        component_index,
4602                        component,
4603                        global_parser_state,
4604                    ) else {
4605                        break;
4606                    };
4607                    local_top_first.push(local);
4608                }
4609                if local_top_first.is_empty() {
4610                    return;
4611                }
4612                local_top_first.reverse();
4613                let local_stack = local_top_first.into_vec();
4614                let local_disallowed =
4615                    self.segmented_local_disallowed(component_index, component, acc);
4616                for local_tokenizer_state in local_tokenizer_states {
4617                    projected_states[component_index].merge_insert(
4618                        local_tokenizer_state,
4619                        ParserGSS::from_single_stack(
4620                            local_stack.clone(),
4621                            local_disallowed.clone(),
4622                        ),
4623                    );
4624                }
4625            });
4626            if !complete {
4627                return false;
4628            }
4629        }
4630
4631        if overlay.segmented_static_baseline {
4632            self.fill_mask_uncached(buf);
4633        } else {
4634            buf.fill(0);
4635        }
4636        #[cfg(test)]
4637        segmented_mask_stage_trace("baseline", buf);
4638        let mut component_times = SmallVec::<[u64; 4]>::new();
4639        let required_component_mask_len = overlay
4640            .segmented_parser_components
4641            .iter()
4642            .zip(projected_states.iter())
4643            .filter(|&(component, state)| !state.is_empty() ).map(|(component, state)| component.constraint.body_mask_len())
4644            .max()
4645            .unwrap_or(0)
4646            .max(buf.len());
4647        let mut scratch = mask_scratch(&self.constraint);
4648        let mut component_buf = if projected_states.iter().any(|state| !state.is_empty()) {
4649            let mut reusable = std::mem::take(&mut scratch.output_buf);
4650            reusable.resize(required_component_mask_len, 0);
4651            Some(reusable)
4652        } else {
4653            None
4654        };
4655        for (component_index, (component, state)) in overlay
4656            .segmented_parser_components
4657            .iter()
4658            .zip(projected_states)
4659            .enumerate()
4660        {
4661            if state.is_empty() {
4662                component_times.push(0);
4663                continue;
4664            }
4665            let component_buf = component_buf
4666                .as_mut()
4667                .expect("active segmented component requires a mask buffer");
4668            let component_started_at = profile.then(Instant::now);
4669            component_buf.fill(0);
4670            let shadow = ConstraintState {
4671                markers: None,
4672                constraint: component.constraint.as_ref().clone(),
4673                state,
4674                epoch: self.generation(),
4675                mask_cache: StateMaskCache::new(),
4676            };
4677            // Dispatch through the retained component itself. Static source
4678            // constraints therefore keep their parser DWA and precomputed mask
4679            // artifacts, while dynamic sources keep their parser/lexer walker.
4680            // A nested hybrid component recursively retains the same split.
4681            shadow.fill_mask(component_buf);
4682            self.or_segmented_component_mask(buf, component_buf);
4683            #[cfg(test)]
4684            segmented_mask_stage_trace(&format!("component-{component_index}"), buf);
4685            component_times.push(component_started_at.map_or(0, elapsed_ns));
4686        }
4687
4688        if let Some(mut reusable) = component_buf.take() {
4689            reusable.clear();
4690            scratch.output_buf = reusable;
4691        }
4692        drop(scratch);
4693        let boundary_started_at = profile.then(Instant::now);
4694        if !self.or_segmented_boundary_shards_mask(overlay, buf) {
4695            return false;
4696        }
4697        #[cfg(test)]
4698        segmented_mask_stage_trace("shards", buf);
4699        let boundary_ns = boundary_started_at.map_or(0, elapsed_ns);
4700        if let Some(started_at) = total_started_at {
4701            eprintln!(
4702                "[glrmask/profile][deterministic_two_dwa_mask] components={} component_ns={component_times:?} boundary_ns={} total_ns={}",
4703                overlay.segmented_parser_components.len(),
4704                boundary_ns,
4705                elapsed_ns(started_at),
4706            );
4707        }
4708        true
4709    }
4710
4711    /// Exact common-case evaluator for a segmented component parser union.
4712    ///
4713    /// Each retained component keeps its original token/TSID coordinate and
4714    /// therefore its existing dense mask caches.  For a concrete parser stack,
4715    /// read the maximal top-first prefix whose composed LR states have a local
4716    /// preimage in that component.  The standalone component DWA has no
4717    /// transition for the first foreign state, so deeper values are semantically
4718    /// irrelevant; truncating there preserves every accepting prefix exactly.
4719    /// Ambiguous GSSes deliberately decline this fast path for now.
4720    fn try_fill_mask_segmented_single_paths(&self, buf: &mut [u32]) -> bool {
4721        let profile_all = crate::env::var_os("GLRMASK_PROFILE_SEGMENTED_MASK").is_some();
4722        let profile_slow = crate::env::var_os("GLRMASK_PROFILE_SEGMENTED_MASK_SLOW").is_some();
4723        let profile = profile_all || profile_slow;
4724        let total_started_at = profile.then(Instant::now);
4725        let Some(overlay) = self.constraint.static_dynamic_overlay.as_ref() else {
4726            return false;
4727        };
4728        if self.constraint.uses_compact_segmented_parser_runtime()
4729            || !overlay.segmented_component_union_root_dispatch.is_empty()
4730        {
4731            return self.try_fill_mask_segmented_deterministic_union(buf);
4732        }
4733        // v22 deliberately flattens all-static retained components into one
4734        // ordinary parser-DWA baseline at save time.  After load the live
4735        // component list can therefore be empty while B remains separately
4736        // serialized and authoritative.  In that shape A comes from
4737        // `fill_mask_uncached` below and this evaluator only needs to OR B.
4738        if overlay.segmented_parser_components.is_empty() && !overlay.segmented_static_baseline {
4739            return false;
4740        }
4741
4742        let mut projected_states = SmallVec::<[ParserStateMap; 4]>::new();
4743        projected_states.resize_with(
4744            overlay.segmented_parser_components.len(),
4745            ParserStateMap::default,
4746        );
4747
4748        for (&global_tokenizer_state, gss) in self.state.iter() {
4749            let complete = gss.for_each_stack_top_first_bounded(128, |top_first, acc| {
4750                for (component_index, component) in
4751                    overlay.segmented_parser_components.iter().enumerate()
4752                {
4753                    let local_tokenizer_states =
4754                        self.segmented_local_tokenizer_states(
4755                            component_index,
4756                            component,
4757                            global_tokenizer_state,
4758                        );
4759                    if local_tokenizer_states.is_empty() {
4760                        continue;
4761                    }
4762
4763                    let mut local_top_first = SmallVec::<[u32; 64]>::new();
4764                    for &global_parser_state in top_first {
4765                        let Some(local) = self.segmented_local_parser_state(
4766                            component_index,
4767                            component,
4768                            global_parser_state,
4769                        ) else {
4770                            break;
4771                        };
4772                        local_top_first.push(local);
4773                    }
4774                    let local_disallowed =
4775                        self.segmented_local_disallowed(component_index, component, acc);
4776                    let local_stack = if local_top_first.is_empty() {
4777                        // An empty *composed* parser stack belongs to the outer
4778                        // parent root.  An empty projection of a non-empty
4779                        // composed stack means instead that this component does
4780                        // not own the current stack top.  In particular, while
4781                        // a child is active the buried parent caller frame must
4782                        // not reactivate parent A (or its scoped ignore) merely
4783                        // because the child's top state has no parent preimage.
4784                        if !top_first.is_empty() || component.terminal_offset != 0 {
4785                            continue;
4786                        }
4787                        Vec::new()
4788                    } else {
4789                        local_top_first.reverse();
4790                        local_top_first.into_vec()
4791                    };
4792                    // Boundary reachability is accounted for separately by B.
4793                    // At a synthetic component root suppress standalone scoped
4794                    // ignore independently in every lifted lexer lane.
4795                    for local_tokenizer_state in local_tokenizer_states {
4796                        let mut branch_disallowed = local_disallowed.clone();
4797                        if local_stack.is_empty()
4798                            && let Some(terminal) = component.root_disallowed_terminal
4799                        {
4800                            branch_disallowed = branch_disallowed.with_insert(
4801                                local_tokenizer_state,
4802                                terminal,
4803                            );
4804                        }
4805                        projected_states[component_index].merge_insert(
4806                            local_tokenizer_state,
4807                            ParserGSS::from_single_stack(
4808                                local_stack.clone(),
4809                                branch_disallowed,
4810                            ),
4811                        );
4812                    }
4813                }
4814            });
4815            if !complete {
4816                return false;
4817            }
4818        }
4819
4820        if overlay.segmented_static_baseline {
4821            self.fill_mask_uncached(buf);
4822        } else {
4823            buf.fill(0);
4824        }
4825        let mut scratch = mask_scratch(&self.constraint);
4826        let mut component_buf = None::<Vec<u32>>;
4827        let mut component_times = SmallVec::<[u64; 4]>::new();
4828        for (component_index, (component, state)) in overlay
4829            .segmented_parser_components
4830            .iter()
4831            .zip(projected_states)
4832            .enumerate()
4833        {
4834            if state.is_empty() {
4835                component_times.push(0);
4836                continue;
4837            }
4838            let component_started_at = profile.then(Instant::now);
4839            let reused_initial = {
4840                match (
4841                    scratch.segmented_component_initial_states.get(component_index),
4842                    scratch.segmented_component_initial_masks.get(component_index),
4843                ) {
4844                    (Some(initial_state), Some(initial_mask)) if initial_state == &state => {
4845                        self.or_segmented_component_mask(buf, initial_mask);
4846                        true
4847                    }
4848                    _ => false,
4849                }
4850            };
4851            if reused_initial {
4852                component_times.push(component_started_at.map_or(0, elapsed_ns));
4853                continue;
4854            }
4855            if component_buf.is_none() {
4856                let mut reusable = std::mem::take(&mut scratch.output_buf);
4857                reusable.resize(
4858                    buf.len().max(component.constraint.body_mask_len()),
4859                    0,
4860                );
4861                component_buf = Some(reusable);
4862            } else if let Some(buffer) = component_buf.as_mut()
4863                && buffer.len() < component.constraint.body_mask_len()
4864            {
4865                buffer.resize(component.constraint.body_mask_len(), 0);
4866            }
4867            let component_buf = component_buf
4868                .as_mut()
4869                .expect("active segmented component requires a mask buffer");
4870            component_buf.fill(0);
4871            let shadow = ConstraintState {
4872                markers: None,
4873                constraint: component.constraint.as_ref().clone(),
4874                state,
4875                epoch: self.generation(),
4876                mask_cache: StateMaskCache::new(),
4877            };
4878            // Preserve the supplied component's runtime backend. A static
4879            // component reuses its compiled parser-DWA/mask machinery; a
4880            // dynamic component keeps using its exact lexer/parser walker.
4881            // Nested segmented components recurse through the same dispatch.
4882            shadow.fill_mask(component_buf);
4883            if crate::env::var_os("GLRMASK_DEBUG_SEGMENTED_COMPONENT_MASK").is_some() {
4884                eprintln!(
4885                    "[glrmask/debug][segmented_component_mask] dynamic={} terminal_offset={} mask={:?} state={:?}",
4886                    component.constraint.uses_dynamic_runtime(),
4887                    component.terminal_offset,
4888                    component_buf,
4889                    shadow.state,
4890                );
4891            }
4892            self.or_segmented_component_mask(buf, component_buf.as_slice());
4893            component_times.push(component_started_at.map_or(0, elapsed_ns));
4894        }
4895        if let Some(mut reusable) = component_buf.take() {
4896            reusable.clear();
4897            scratch.output_buf = reusable;
4898        }
4899        drop(scratch);
4900        let boundary_started_at = profile.then(Instant::now);
4901        if !self.or_segmented_boundary_shards_mask(overlay, buf) {
4902            return false;
4903        }
4904        let boundary_ns = boundary_started_at.map_or(0, elapsed_ns);
4905        if let Some(started_at) = total_started_at {
4906            let total_ns = elapsed_ns(started_at);
4907            if profile_all || total_ns >= 100_000 {
4908                eprintln!(
4909                    "[glrmask/profile][segmented_parser_mask] components={} component_ns={component_times:?} boundary_ns={} total_ns={}",
4910                    overlay.segmented_parser_components.len(),
4911                    boundary_ns,
4912                    total_ns,
4913                );
4914            }
4915        }
4916        true
4917    }
4918
4919    /// Test-only: report one boundary shard's mask contribution by snapshot
4920    /// diff, together with the effective top state / source context that made
4921    /// it active. Enabled by `GLRMASK_DEBUG_MASK_STAGES`.
4922    #[cfg(test)]
4923    fn trace_segmented_shard_delta(
4924        &self,
4925        component_index: usize,
4926        shard: &crate::runtime::SegmentedBoundaryShard,
4927        before: &[u32],
4928        after: &[u32],
4929    ) {
4930        if !segmented_mask_stage_trace_enabled() {
4931            return;
4932        }
4933        let mut added = Vec::new();
4934        for (word_index, (&before_word, &after_word)) in
4935            before.iter().zip(after.iter()).enumerate()
4936        {
4937            let mut delta = after_word & !before_word;
4938            while delta != 0 {
4939                let bit = delta.trailing_zeros() as usize;
4940                added.push((word_index * 32 + bit) as u32);
4941                delta &= delta - 1;
4942            }
4943        }
4944        let compact = self.constraint.uses_compact_segmented_parser_runtime();
4945        let mut contexts = Vec::new();
4946        for (&global_tokenizer_state, gss) in self.state.iter() {
4947            let _ = gss.for_each_stack_top_first_bounded(128, |top_first, _| {
4948                match top_first.first().copied() {
4949                    Some(top) => {
4950                        let owner = if compact {
4951                            self.constraint
4952                                .compact_segmented_parser_component(top)
4953                                .map(|(component, _)| component as u32)
4954                        } else {
4955                            shard
4956                                .start_parser_states
4957                                .contains(top as usize)
4958                                .then_some(shard.start_component)
4959                        };
4960                        contexts.push(format!(
4961                            "gts={global_tokenizer_state} top={top} owner={owner:?} active={}",
4962                            owner == Some(shard.start_component),
4963                        ));
4964                    }
4965                    None => contexts.push(format!(
4966                        "gts={global_tokenizer_state} empty_stack active={}",
4967                        shard.accepts_empty_stack,
4968                    )),
4969                }
4970            });
4971        }
4972        let backend = match &shard.backend {
4973            crate::runtime::SegmentedBoundaryShardBackend::StaticParser(_) => "StaticParser",
4974            crate::runtime::SegmentedBoundaryShardBackend::DynamicTerminalTrie(_) => {
4975                "DynamicTerminalTrie"
4976            }
4977            crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect => "DynamicDirect",
4978        };
4979        let candidates = shard
4980            .candidate_tokens
4981            .as_ref()
4982            .map(|tokens| tokens.iter().copied().collect::<Vec<_>>())
4983            .unwrap_or_default();
4984        eprintln!(
4985            "[mask-stages] shard[{component_index}] backend={backend} start_component={} candidates={candidates:?} added_bits={added:?} token8={} token9={} contexts={contexts:?}",
4986            shard.start_component,
4987            added.contains(&8),
4988            added.contains(&9),
4989        );
4990    }
4991
4992    // Keep the diagnostic scope outside the implementation's stack-frame
4993    // prologue/epilogue. Otherwise its large shadow-state frame is incorrectly
4994    // charged to non-boundary work by whole-minus-dispatch accounting.
4995    #[inline(always)]
4996    fn or_segmented_boundary_shards_mask(
4997        &self,
4998        overlay: &crate::runtime::StaticDynamicOverlayMetadata,
4999        buf: &mut [u32],
5000    ) -> bool {
5001        #[cfg(any(test, feature = "internal-api"))]
5002        let _boundary_cpu = super::boundary_cpu_profile::Span::enter(super::boundary_cpu_profile::Kind::Dispatch);
5003        self.or_segmented_boundary_shards_mask_impl(overlay, buf)
5004    }
5005
5006    #[inline(never)]
5007    fn or_segmented_boundary_shards_mask_impl(
5008        &self,
5009        overlay: &crate::runtime::StaticDynamicOverlayMetadata,
5010        buf: &mut [u32],
5011    ) -> bool {
5012        if overlay
5013            .segmented_parser_components
5014            .iter()
5015            .any(|component| component.boundary.is_some())
5016        {
5017            let mut needs_direct_dynamic = false;
5018            // Vocabulary preparation is binding-local and done once; execution
5019            // remains the same shared optimized dynamic walker as ordinary masks.
5020            let restricted = crate::env::var_os("GLRMASK_DISABLE_BOUNDARY_VOCAB").is_none();
5021            for (component_index, component) in
5022                overlay.segmented_parser_components.iter().enumerate()
5023            {
5024                let Some(shard) = component.boundary.as_ref() else {
5025                    continue;
5026                };
5027                debug_assert_eq!(shard.start_component as usize, component_index);
5028                #[cfg(test)]
5029                let before_shard = segmented_mask_stage_trace_enabled().then(|| buf.to_vec());
5030                let ok = match &shard.backend {
5031                    crate::runtime::SegmentedBoundaryShardBackend::StaticParser(boundary) => {
5032                        self.or_segmented_boundary_parser_mask(
5033                            boundary,
5034                            Some(&shard.start_parser_states),
5035                            Some(shard.start_component),
5036                            shard.accepts_empty_stack,
5037                            buf,
5038                        )
5039                    }
5040                    crate::runtime::SegmentedBoundaryShardBackend::DynamicTerminalTrie(boundary) => {
5041                        self.or_segmented_boundary_terminal_trie_mask(
5042                            boundary,
5043                            Some(&shard.start_parser_states),
5044                            shard.accepts_empty_stack,
5045                            buf,
5046                        )
5047                    }
5048                    crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect => {
5049                        #[cfg(any(test, feature = "internal-api"))]
5050                        let _dynamic_cpu = super::boundary_cpu_profile::Span::enter(super::boundary_cpu_profile::Kind::Dynamic);
5051                        if !self.segmented_boundary_shard_may_be_active(shard) {
5052                            continue;
5053                        }
5054                        // Strict-static trap (milestone H): a claimed static
5055                        // path must never silently evaluate DynamicDirect
5056                        // masks. Env-gated so exact dynamic compositions are
5057                        // unaffected; strict-static tests set
5058                        // GLRMASK_STRICT_STATIC_TRAP_DYNAMIC=1 and any firing
5059                        // DynamicDirect shard panics loudly here instead of
5060                        // contributing hidden dynamic admissions.
5061                        crate::compiler::boundary_transfer::strict_static_trap_dynamic_for_state(
5062                            "segmented_dynamic_direct_shard",
5063                            self.constraint.uses_dynamic_runtime(),
5064                        );
5065                        let handled = restricted && shard.candidate_tokens.as_deref().is_some_and(|ids| {
5066                            let prepared = shard.mask_vocabulary.get_or_init(|| {
5067                                super::dynamic_mask::PreparedMaskVocabulary::new(&self.constraint, ids)
5068                            });
5069                            prepared.as_ref().ok().is_some_and(|vocab| {
5070                                if crate::env::var_os("GLRMASK_DISABLE_BOUNDARY_FRONTIER_SELECTION").is_some() {
5071                                    return vocab.or_mask(self, buf).expect("exact vocabulary mask failed");
5072                                }
5073                                let Some(frontier) = self.segmented_boundary_initial_frontier(shard)
5074                                    else { return false; };
5075                                if frontier.is_empty() { return true; }
5076                                if crate::env::var_os("GLRMASK_PROFILE_DYNAMIC_BOUNDARY_CANDIDATE_TRIE").is_some() {
5077                                    eprintln!("[glrmask/profile][boundary_initial_frontier] component={} before={} after={}",
5078                                        shard.start_component, self.state.len(), frontier.len());
5079                                }
5080                                let view = ConstraintState {
5081                                    markers: None,
5082                                    constraint: self.constraint.clone(),
5083                                    state: frontier,
5084                                    epoch: self.epoch,
5085                                    mask_cache: StateMaskCache::new(),
5086                                };
5087                                vocab.or_mask(&view, buf).expect("exact vocabulary mask failed")
5088                            })
5089                        });
5090                        needs_direct_dynamic |= !handled;
5091                        true
5092                    }
5093                };
5094                #[cfg(test)]
5095                if let Some(before_shard) = before_shard {
5096                    self.trace_segmented_shard_delta(component_index, shard, &before_shard, buf);
5097                }
5098                if !ok {
5099                    return false;
5100                }
5101            }
5102            if needs_direct_dynamic {
5103                #[cfg(any(test, feature = "internal-api"))]
5104                let _fallback_cpu = super::boundary_cpu_profile::Span::enter(super::boundary_cpu_profile::Kind::Dynamic);
5105                // A DynamicDirect shard owned a live stack on a path that also
5106                // evaluated static shards. The per-shard arm above already
5107                // traps loudly under the strict flag; this second trap names
5108                // the unified/recursive walker fallback itself so a missed arm
5109                // cannot silently contribute exact dynamic admissions.
5110                crate::compiler::boundary_transfer::strict_static_trap_dynamic_for_state(
5111                    "segmented_boundary_needs_direct_dynamic",
5112                    self.constraint.uses_dynamic_runtime(),
5113                );
5114                if self.constraint.uses_compact_segmented_parser_runtime() {
5115                    // Use the same shared provider walk as all-dynamic
5116                    // composition, then union with the static contribution.
5117                    let mut dynamic = vec![0u32; self.constraint.mask_bit_len().div_ceil(32)];
5118                    self.fill_mask_dynamic(&mut dynamic);
5119                    for (out, value) in buf.iter_mut().zip(dynamic) { *out |= value; }
5120                } else {
5121                    // The unified strict walker evaluates the complete exact
5122                    // composed language and ORs it with the already-computed A
5123                    // baseline. No B-domain candidate discovery is needed.
5124                    super::dynamic_mask::or_mask_dynamic_additions(self, buf);
5125                }
5126            }
5127            return true;
5128        }
5129
5130        // v22/legacy in-memory compatibility while boundary shards are being
5131        // versioned into the wire format.
5132        if let Some(boundary) = overlay.segmented_boundary_parser.as_deref()
5133            && !self.or_segmented_boundary_parser_mask(boundary, None, None, true, buf)
5134        {
5135            return false;
5136        }
5137        if let Some(boundary) = overlay.segmented_boundary_terminal_trie.as_deref()
5138            && !self.or_segmented_boundary_terminal_trie_mask(boundary, None, true, buf)
5139        {
5140            return false;
5141        }
5142        true
5143    }
5144
5145    /// Independent test oracle retained from the pre-unification recursive
5146    /// walker. Production recursive masking uses the ordinary shared traversal
5147    /// with finite/config scoped providers in dynamic_mask.
5148    #[cfg(test)]
5149    fn or_recursive_dynamic_full_walk_exact(&self, buf: &mut [u32]) {
5150        self.or_recursive_dynamic_full_walk_exact_with_budget(buf, 256);
5151    }
5152
5153    #[cfg(test)]
5154    fn or_recursive_dynamic_full_walk_exact_with_budget(&self, buf: &mut [u32], state_budget: usize) {
5155        crate::compiler::boundary_transfer::strict_static_trap_dynamic_for_state(
5156            "or_recursive_dynamic_full_walk_exact",
5157            self.constraint.uses_dynamic_runtime(),
5158        );
5159        let vocab = self.constraint.dynamic_mask_vocab_for_runtime();
5160        let trie = vocab.trie.as_ref();
5161        let stack_len = usize::from(trie.full_walk_max_parent_depth()).saturating_add(2);
5162        let mut state_stack = vec![None; stack_len.max(1)];
5163        let alphabet = if state_budget == 0 { std::array::from_fn(|byte| byte as u8) }
5164            else { recursive_mask_byte_representatives(&self.constraint) };
5165        // A proved finite deterministic leaf alphabet cannot produce a wide
5166        // epsilon frontier. The recursive queue does not use speculative flat
5167        // commits, so it needs no eager pool of 256 flat-frontier GSS objects.
5168        // Keep the established scratch policy for unproved/virtual lexers.
5169        let mut buffers = if alphabet.iter().enumerate().any(|(i, &b)| i != b as usize) {
5170            CommitBuffers::for_finite_recursive_mask()
5171        } else {
5172            CommitBuffers::default()
5173        };
5174        let mut transitions = RecursiveMaskTransitions::new(state_budget, alphabet);
5175        state_stack[0] = Some(match transitions.intern(&self.state) {
5176            Some(id) => RecursiveMaskFrontier::Cached(id),
5177            None => RecursiveMaskFrontier::Uncached(self.state.clone()),
5178        });
5179
5180        let mark_node = |node: u32, live: bool, buf: &mut [u32]| {
5181            if !live {
5182                return;
5183            }
5184            let Some(canonical) = trie.node(node).token_id else {
5185                return;
5186            };
5187            let Some(token_ids) = vocab.token_ids(canonical) else {
5188                return;
5189            };
5190            for &token_id in token_ids {
5191                // A token id with explicit special-token semantics denotes the
5192                // union of its byte and special routes. Probe it once through
5193                // authoritative token commit below rather than accepting from
5194                // only the byte route here.
5195                if !self.constraint.has_special_token_id(token_id) {
5196                    set_original_mask_bit(buf, token_id);
5197                }
5198            }
5199        };
5200
5201        // A zero-byte vocabulary entry lives on the radix-trie root. It is not
5202        // an ordinary model-token byte route because consuming it would make
5203        // no byte progress. Explicit grammar special-token semantics for the
5204        // same ID are handled pointwise below.
5205        let edges = trie.walk_edges();
5206        let mut edge_index = 0;
5207        while let Some(edge) = edges.get(edge_index) {
5208            let parent_depth = edge.parent_depth as usize;
5209            let child_depth = parent_depth + 1;
5210            let child_state = state_stack[parent_depth].as_ref().and_then(|parent| {
5211                transitions.advance(
5212                    &self.constraint,
5213                    parent,
5214                    &mut buffers,
5215                    trie.walk_edge_bytes(edge),
5216                )
5217            });
5218            let live = child_state.is_some();
5219            state_stack[child_depth] = child_state;
5220            if !live {
5221                // Exact byte advancement has rejected this prefix. Previously
5222                // its descendants were still visited, but their absent parent
5223                // states suppressed every semantic advance and token mark.
5224                // Skip precisely that same work using the existing DFS jump;
5225                // no boundary-candidate or lexer-liveness approximation is
5226                // involved. The next edge's parent is an already-live ancestor,
5227                // so stale deeper stack slots cannot be read before replacement.
5228                // Special-token routes remain independent and are probed below.
5229                debug_assert!(edge.subtree_end as usize > edge_index);
5230                edge_index = edge.subtree_end as usize;
5231                continue;
5232            }
5233            mark_node(edge.child, live, buf);
5234            edge_index += 1;
5235        }
5236
5237        // Special-token semantics can add a parser path independent of the
5238        // token's byte spelling, so those ids deliberately stay pointwise.
5239        let mut pointwise_candidates = self
5240            .constraint
5241            .special_token_terminals
5242            .iter()
5243            .filter(|special| {
5244                !self
5245                    .constraint
5246                    .is_late_grammar_placeholder_terminal(special.terminal_id)
5247            })
5248            .flat_map(|special| special.token_ids())
5249            .collect::<Vec<_>>();
5250        pointwise_candidates.sort_unstable();
5251        pointwise_candidates.dedup();
5252        for token_id in pointwise_candidates {
5253            let admitted = if self
5254                .constraint
5255                .token_bytes_for_id(token_id)
5256                .is_some_and(|bytes| bytes.is_empty())
5257            {
5258                // The byte trie represents an empty vocabulary token at its
5259                // root. Exact special-token IDs with that spelling are
5260                // deliberately pointwise: an empty byte spelling must not
5261                // become a zero-progress alternate route that bypasses the
5262                // parser's special-token terminal.
5263                crate::runtime::commit::advance_special_token_paths(
5264                    &self.constraint,
5265                    &self.state,
5266                    token_id,
5267                )
5268                .is_some_and(|gss| !gss.is_empty())
5269            } else {
5270                crate::runtime::commit::token_admissible_from_state_exact(
5271                    &self.constraint,
5272                    &self.state,
5273                    &mut buffers,
5274                    token_id,
5275                )
5276            };
5277            if admitted {
5278                set_original_mask_bit(buf, token_id);
5279            }
5280        }
5281    }
5282
5283    /// Independent pre-unification mask oracle, compiled only for tests.
5284    #[cfg(test)]
5285    pub(crate) fn fill_recursive_mask_by_exact_full_walk(&self, buf: &mut [u32]) {
5286        crate::compiler::boundary_transfer::strict_static_trap_dynamic_for_state(
5287            "fill_recursive_mask_by_exact_full_walk",
5288            self.constraint.uses_dynamic_runtime(),
5289        );
5290        buf.fill(0);
5291        self.or_recursive_dynamic_full_walk_exact(buf);
5292    }
5293
5294    fn or_segmented_boundary_terminal_trie_mask(
5295        &self,
5296        boundary: &crate::runtime::SegmentedBoundaryTerminalTrie,
5297        start_parser_states: Option<&crate::ds::bitset::BitSet>,
5298        accepts_empty_stack: bool,
5299        buf: &mut [u32],
5300    ) -> bool {
5301        const MAX_NWA_PRODUCT_ENTRIES: usize = 4096;
5302
5303        fn dense_contains(acc: &DenseMaskAcc, token: u32) -> bool {
5304            let word = token as usize / 64;
5305            let bit = token % 64;
5306            acc.0.iter().any(|(_, dense)| {
5307                dense.get(word)
5308                    .is_some_and(|word_value| (*word_value & (1u64 << bit)) != 0)
5309            })
5310        }
5311
5312        #[derive(Clone)]
5313        enum BoundaryTokenDomain {
5314            Full,
5315            Set(Arc<RangeSetBlaze<u32>>),
5316        }
5317
5318        fn same_domain(left: &BoundaryTokenDomain, right: &BoundaryTokenDomain) -> bool {
5319            match (left, right) {
5320                (BoundaryTokenDomain::Full, BoundaryTokenDomain::Full) => true,
5321                (BoundaryTokenDomain::Set(left), BoundaryTokenDomain::Set(right)) => {
5322                    Arc::ptr_eq(left, right) || left.as_ref() == right.as_ref()
5323                }
5324                _ => false,
5325            }
5326        }
5327
5328        fn intersect_domain(
5329            current: &BoundaryTokenDomain,
5330            edge: &Weight,
5331            tsid: u32,
5332        ) -> Option<BoundaryTokenDomain> {
5333            if edge.is_empty() {
5334                return None;
5335            }
5336            if edge.is_full() {
5337                return Some(current.clone());
5338            }
5339            let edge_tokens = edge.token_set_for_tsid_ref(tsid)?;
5340            match current {
5341                BoundaryTokenDomain::Full => {
5342                    Some(BoundaryTokenDomain::Set(Arc::clone(edge_tokens)))
5343                }
5344                BoundaryTokenDomain::Set(current_tokens) => {
5345                    if Arc::ptr_eq(current_tokens, edge_tokens)
5346                        || current_tokens.as_ref() == edge_tokens.as_ref()
5347                    {
5348                        return Some(current.clone());
5349                    }
5350                    if current_tokens.as_ref().is_disjoint(edge_tokens.as_ref()) {
5351                        return None;
5352                    }
5353                    let overlap = current_tokens.as_ref() & edge_tokens.as_ref();
5354                    (!overlap.is_empty())
5355                        .then(|| BoundaryTokenDomain::Set(Arc::new(overlap)))
5356                }
5357            }
5358        }
5359
5360        type ProductBucket = SmallVec<[(BoundaryTokenDomain, ParserGSS); 4]>;
5361
5362        fn push_product(
5363            bucket: &mut ProductBucket,
5364            domain: BoundaryTokenDomain,
5365            parser: ParserGSS,
5366        ) {
5367            if let Some((_, existing_parser)) = bucket
5368                .iter_mut()
5369                .find(|(existing_domain, _)| same_domain(existing_domain, &domain))
5370            {
5371                *existing_parser = existing_parser.merge(&parser);
5372            } else {
5373                bucket.push((domain, parser));
5374            }
5375        }
5376
5377        for (&global_tokenizer_state, gss) in self.state.iter() {
5378            let tsid = boundary
5379                .tokenizer_state_to_tsid
5380                .get(global_tokenizer_state as usize)
5381                .copied()
5382                .unwrap_or(u32::MAX);
5383            if tsid == u32::MAX {
5384                continue;
5385            }
5386
5387            let mut complete = true;
5388            let single_path = gss.is_single_path();
5389            let traversal_complete = gss.for_each_stack_top_first_bounded(128, |top_first, acc| {
5390                if let Some(start_parser_states) = start_parser_states {
5391                    match top_first.first().copied() {
5392                        Some(top) if !start_parser_states.contains(top as usize) => return,
5393                        None if !accepts_empty_stack => return,
5394                        _ => {}
5395                    }
5396                }
5397                let Some(allowed) =
5398                    self.terminals_disallowed_to_dense_acc(acc, global_tokenizer_state)
5399                else {
5400                    complete = false;
5401                    return;
5402                };
5403                let parser = if single_path {
5404                    gss.clone()
5405                } else {
5406                    let mut stack = SmallVec::<[u32; 64]>::from_slice(top_first);
5407                    stack.reverse();
5408                    ParserGSS::from_single_stack(stack.into_vec(), acc.clone())
5409                };
5410
5411                let mut admit_internal_token = |internal_token: u32| -> bool {
5412                    let Some(originals) = boundary
5413                        .internal_token_to_originals
5414                        .get(internal_token as usize)
5415                    else {
5416                        return false;
5417                    };
5418                    for &original in originals {
5419                        let outer_internal = self
5420                            .constraint
5421                            .original_token_internal_at(original)
5422                            .unwrap_or(u32::MAX);
5423                        let outer_allowed = outer_internal != u32::MAX
5424                            && dense_contains(&allowed, outer_internal);
5425                        if outer_allowed {
5426                            set_original_mask_bit(buf, original);
5427                        }
5428                    }
5429                    true
5430                };
5431
5432                if let Some(nwa) = boundary.symbolic_nwa.as_ref() {
5433                    let mut buckets = SmallVec::<[ProductBucket; 16]>::new();
5434                    buckets.resize_with(nwa.nodes.len(), ProductBucket::new);
5435                    for &start in &nwa.start_states {
5436                        let Some(bucket) = buckets.get_mut(start as usize) else {
5437                            complete = false;
5438                            return;
5439                        };
5440                        push_product(bucket, BoundaryTokenDomain::Full, parser.clone());
5441                    }
5442
5443                    let mut product_entries = 0usize;
5444                    for &state_id in &nwa.topological_order {
5445                        let Some(bucket) = buckets.get_mut(state_id as usize) else {
5446                            complete = false;
5447                            return;
5448                        };
5449                        let entries = std::mem::take(bucket);
5450                        if entries.is_empty() {
5451                            continue;
5452                        }
5453                        product_entries = product_entries.saturating_add(entries.len());
5454                        if product_entries > MAX_NWA_PRODUCT_ENTRIES {
5455                            complete = false;
5456                            return;
5457                        }
5458                        let Some(node) = nwa.nodes.get(state_id as usize) else {
5459                            complete = false;
5460                            return;
5461                        };
5462                        for (domain, parser) in entries {
5463                            if let Some(final_weight) = node.final_weight.as_ref()
5464                                && let Some(output_domain) =
5465                                    intersect_domain(&domain, final_weight, tsid)
5466                            {
5467                                match output_domain {
5468                                    BoundaryTokenDomain::Full => {
5469                                        for internal_token in
5470                                            0..boundary.internal_token_to_originals.len() as u32
5471                                        {
5472                                            if !admit_internal_token(internal_token) {
5473                                                complete = false;
5474                                                return;
5475                                            }
5476                                        }
5477                                    }
5478                                    BoundaryTokenDomain::Set(tokens) => {
5479                                        for range in tokens.ranges() {
5480                                            for internal_token in range {
5481                                                if !admit_internal_token(internal_token) {
5482                                                    complete = false;
5483                                                    return;
5484                                                }
5485                                            }
5486                                        }
5487                                    }
5488                                }
5489                            }
5490
5491                            for (target, edge_weight) in &node.epsilons {
5492                                let Some(next_domain) =
5493                                    intersect_domain(&domain, edge_weight, tsid)
5494                                else {
5495                                    continue;
5496                                };
5497                                let Some(target_bucket) = buckets.get_mut(*target as usize) else {
5498                                    complete = false;
5499                                    return;
5500                                };
5501                                push_product(target_bucket, next_domain, parser.clone());
5502                            }
5503                            for transition in &node.transitions {
5504                                let Some(next_domain) =
5505                                    intersect_domain(&domain, &transition.weight, tsid)
5506                                else {
5507                                    continue;
5508                                };
5509                                let advanced = super::commit::advance_parser_stacks_table_exact(
5510                                    &self.constraint,
5511                                    &parser,
5512                                    transition.terminal,
5513                                );
5514                                let Some(advanced) = advanced else {
5515                                    continue;
5516                                };
5517                                if advanced.is_empty() {
5518                                    continue;
5519                                }
5520                                let Some(target_bucket) =
5521                                    buckets.get_mut(transition.target as usize)
5522                                else {
5523                                    complete = false;
5524                                    return;
5525                                };
5526                                push_product(target_bucket, next_domain, advanced);
5527                            }
5528                        }
5529                    }
5530                    return;
5531                }
5532
5533                // Legacy v21 artifacts carry an explicitly expanded trie. Keep
5534                // that evaluator unchanged for backwards compatibility.
5535                let root = boundary
5536                    .root_by_tsid
5537                    .get(tsid as usize)
5538                    .copied()
5539                    .unwrap_or(u32::MAX);
5540                if root == u32::MAX {
5541                    return;
5542                }
5543                let mut pending = Vec::<(u32, ParserGSS)>::new();
5544                pending.push((root, parser));
5545                let mut visits = 0usize;
5546                while let Some((node_id, parser)) = pending.pop() {
5547                    visits += 1;
5548                    if visits > boundary.nodes.len().saturating_mul(2).max(32) {
5549                        complete = false;
5550                        return;
5551                    }
5552                    let Some(node) = boundary.nodes.get(node_id as usize) else {
5553                        complete = false;
5554                        return;
5555                    };
5556                    for &internal_token in &node.outputs {
5557                        if !admit_internal_token(internal_token) {
5558                            complete = false;
5559                            return;
5560                        }
5561                    }
5562                    for &(terminal, child) in &node.children {
5563                        if let Some(advanced) = super::commit::advance_parser_stacks_table_exact(
5564                            &self.constraint,
5565                            &parser,
5566                            terminal,
5567                        ) && !advanced.is_empty()
5568                        {
5569                            pending.push((child, advanced));
5570                        }
5571                    }
5572                }
5573            });
5574            if !traversal_complete || !complete {
5575                return false;
5576            }
5577        }
5578        true
5579    }
5580
5581    /// Conservatively test whether this shard can own at least one current
5582    /// composed parser-stack top. Incomplete bounded GSS inspection returns
5583    /// true so trigger acceleration can never create a false negative.
5584    fn segmented_boundary_shard_may_be_active(
5585        &self,
5586        shard: &crate::runtime::SegmentedBoundaryShard,
5587    ) -> bool {
5588        // Ownership depends only on the top, not on an enumeration of entire
5589        // stacks. peek_values is an exact union over all GSS top alternatives.
5590        for gss in self.state.values() {
5591            if shard.accepts_empty_stack && !gss.isolate(None).is_empty() { return true; }
5592            for top in gss.peek_values() {
5593                let belongs = if self.constraint.uses_compact_segmented_parser_runtime() {
5594                    self.constraint.compact_segmented_parser_component(top)
5595                        .is_some_and(|(owner, _)| owner == shard.start_component as usize)
5596                } else { shard.start_parser_states.contains(top as usize) };
5597                if belongs { return true; }
5598            }
5599        }
5600        false
5601    }
5602
5603    /// Select the initial relation belonging to one vocabulary shard. Keep
5604    /// whole lower stacks and exclusion accumulators; never enumerate or cut
5605    /// stack paths. This is input selection for the ordinary shared walker.
5606    fn segmented_boundary_initial_frontier(
5607        &self,
5608        shard: &crate::runtime::SegmentedBoundaryShard,
5609    ) -> Option<ParserStateMap> {
5610        if !self.constraint.uses_compact_segmented_parser_runtime() { return None; }
5611        let mut selected = ParserStateMap::default();
5612        for (&lexer, gss) in self.state.iter() {
5613            if gss.is_empty() { continue; }
5614            let tops = gss.peek_values();
5615            let mut keep = SmallVec::<[u32; 4]>::new();
5616            for &top in &tops {
5617                let (owner, _) = self.constraint.compact_segmented_parser_component(top)?;
5618                if owner == shard.start_component as usize { keep.push(top); }
5619            }
5620            let empty = gss.isolate(None);
5621            let branch = if keep.len() == tops.len() && (shard.accepts_empty_stack || empty.is_empty()) {
5622                gss.clone()
5623            } else {
5624                let mut branch = if shard.accepts_empty_stack { empty } else { ParserGSS::empty() };
5625                for top in keep { branch = branch.merge(&gss.isolate(Some(top))); }
5626                branch
5627            };
5628            if !branch.is_empty() { selected.insert_flat_alternative(lexer, branch); }
5629        }
5630        Some(selected)
5631    }
5632
5633    /// OR exact component-trigger candidates into `buf`. Trigger parser labels
5634    /// are component-local LR IDs, but its weight coordinate is deliberately
5635    /// raw/original: TSID == local tokenizer-state ID and token == original
5636    /// model-token ID. This avoids assuming that the ordinary whole-token
5637    /// TSID/token quotient also preserves proper-prefix boundary observations.
5638    /// This routine intentionally ignores terminal exclusions: doing so can
5639    /// only add false-positive candidates and therefore remains a sound gate
5640    /// for the exact dynamic crossing evaluator.
5641    fn or_exact_component_trigger_candidates(
5642        &self,
5643        component: &crate::runtime::SegmentedParserComponent,
5644        shard: &crate::runtime::SegmentedBoundaryShard,
5645        dwa: &crate::automata::weighted_u32::dwa::DWA,
5646        buf: &mut [u32],
5647    ) -> bool {
5648        if component.constraint.has_recursive_segmented_parser_tree() {
5649            // Exact trigger labels are still compiled in this component's
5650            // transitional materialized-table coordinate. Once its parser is
5651            // projected recursively, feeding those leaf-scoped states to the
5652            // trigger DWA would be unsound. Decline the accelerator; recursive
5653            // DynamicDirect B will validate the resulting token domain through
5654            // exact scoped commits. Trigger metadata is pruning only, never
5655            // semantics.
5656            return false;
5657        }
5658        for (&global_tokenizer_state, gss) in self.state.iter() {
5659            let local_tokenizer_states = self.segmented_local_tokenizer_states(
5660                shard.start_component as usize,
5661                component,
5662                global_tokenizer_state,
5663            );
5664            if local_tokenizer_states.is_empty() {
5665                // An unmappable lexer state is harmless only when this
5666                // component cannot own any stack at that lexer key. If an
5667                // active shard is present, declining Exact is mandatory:
5668                // silently skipping the key could remove real trigger tokens
5669                // and create a false-negative dynamic-boundary gate.
5670                let mut active = false;
5671                let traversal_complete =
5672                    gss.for_each_stack_top_first_bounded(128, |top_first, _| {
5673                        if active {
5674                            return;
5675                        }
5676                        active = match top_first.first().copied() {
5677                            Some(top) if self.constraint.uses_compact_segmented_parser_runtime() => {
5678                                self.constraint
5679                                    .compact_segmented_parser_component(top)
5680                                    .is_some_and(|(owner, _)| owner == shard.start_component as usize)
5681                            }
5682                            Some(top) => shard.start_parser_states.contains(top as usize),
5683                            None => shard.accepts_empty_stack,
5684                        };
5685                    });
5686                if !traversal_complete || active {
5687                    return false;
5688                }
5689                continue;
5690            }
5691            let mut complete = true;
5692            let traversal_complete = gss.for_each_stack_top_first_bounded(128, |top_first, _| {
5693                match top_first.first().copied() {
5694                    Some(top) if self.constraint.uses_compact_segmented_parser_runtime() => {
5695                        if self
5696                            .constraint
5697                            .compact_segmented_parser_component(top).is_none_or(|(owner, _)| owner != shard.start_component as usize)
5698                        {
5699                            return;
5700                        }
5701                    }
5702                    Some(top) if !shard.start_parser_states.contains(top as usize) => return,
5703                    None if !shard.accepts_empty_stack => return,
5704                    _ => {}
5705                }
5706
5707                let mut local_top_first = SmallVec::<[u32; 64]>::new();
5708                let mut projection_truncated = false;
5709                for &global_parser_state in top_first {
5710                    let Some(local) = self.segmented_local_parser_state(
5711                        shard.start_component as usize,
5712                        component,
5713                        global_parser_state,
5714                    ) else {
5715                        if !self.constraint.uses_compact_segmented_parser_runtime() {
5716                            projection_truncated = true;
5717                        }
5718                        break;
5719                    };
5720                    local_top_first.push(local);
5721                }
5722                if projection_truncated || (!top_first.is_empty() && local_top_first.is_empty()) {
5723                    // Do not evaluate a trigger language on a silently
5724                    // truncated local stack.  A future scoped-GSS proof may
5725                    // certify the first foreign state as exactly the caller
5726                    // boundary; until then, fallback to the unified dynamic
5727                    // recognizer rather than risk losing a deeper-stack
5728                    // readiness condition.
5729                    complete = false;
5730                    return;
5731                }
5732
5733                let accepted = exact_component_trigger_accepted_weight(
5734                    component.constraint.as_ref(),
5735                    dwa,
5736                    &local_top_first,
5737                );
5738                if accepted.is_empty() {
5739                    return;
5740                }
5741                // Exact trigger construction always leaves the lexical path
5742                // support attached, so a universal final result is malformed
5743                // for this artifact. Decline rather than interpreting it as a
5744                // huge token universe and risk masking a coordinate bug.
5745                if accepted.is_full() {
5746                    complete = false;
5747                    return;
5748                }
5749                for &local_tokenizer_state in &local_tokenizer_states {
5750                    let tokens = accepted.tokens_for_tsid(local_tokenizer_state);
5751                    for original_token in tokens.iter() {
5752                        set_original_mask_bit(buf, original_token);
5753                    }
5754                }
5755            });
5756            if !traversal_complete || !complete {
5757                return false;
5758            }
5759        }
5760        true
5761    }
5762
5763    /// Admit one exact-DAG group's accepted Weight into `buf`, preserving the
5764    /// per-path eligibility correlation (the group already unions exactly the
5765    /// paths sharing its accumulator). Returns `false` to decline when an
5766    /// internal token has no original mapping; the caller then runs the exact
5767    /// fallback (which the strict-static trap turns into a loud panic).
5768    fn admit_boundary_weight_group(
5769        &self,
5770        boundary: &crate::runtime::SegmentedBoundaryParser,
5771        accepted: &Weight,
5772        boundary_tsids: &[u32],
5773        allowed: &DenseMaskAcc,
5774        buf: &mut [u32],
5775    ) -> bool {
5776        fn dense_contains(acc: &DenseMaskAcc, token: u32) -> bool {
5777            let word = token as usize / 64;
5778            let bit = token % 64;
5779            acc.0.iter().any(|(_, dense)| {
5780                dense.get(word)
5781                    .is_some_and(|word_value| (*word_value & (1u64 << bit)) != 0)
5782            })
5783        }
5784        for &boundary_tsid in boundary_tsids {
5785            let Some(tokens) = accepted.token_set_for_tsid_ref(boundary_tsid) else {
5786                continue;
5787            };
5788            for range in tokens.ranges() {
5789                for internal_token in range {
5790                    let Some(originals) = boundary
5791                        .internal_token_to_originals
5792                        .get(internal_token as usize)
5793                    else {
5794                        return false;
5795                    };
5796                    for &original in originals {
5797                        let outer_internal = self
5798                            .constraint
5799                            .original_token_internal_at(original)
5800                            .unwrap_or(u32::MAX);
5801                        if outer_internal != u32::MAX && dense_contains(allowed, outer_internal)
5802                        {
5803                            set_original_mask_bit(buf, original);
5804                        }
5805                    }
5806                }
5807            }
5808        }
5809        true
5810    }
5811
5812    /// Admit one exact-DAG group's accepted compact u64 mask into `buf`.
5813    /// Same decline contract as `admit_boundary_weight_group`.
5814    fn admit_boundary_mask64_group(
5815        &self,
5816        boundary: &crate::runtime::SegmentedBoundaryParser,
5817        mut accepted: u64,
5818        allowed: &DenseMaskAcc,
5819        buf: &mut [u32],
5820    ) -> bool {
5821        fn dense_contains(acc: &DenseMaskAcc, token: u32) -> bool {
5822            let word = token as usize / 64;
5823            let bit = token % 64;
5824            acc.0.iter().any(|(_, dense)| {
5825                dense.get(word)
5826                    .is_some_and(|word_value| (*word_value & (1u64 << bit)) != 0)
5827            })
5828        }
5829        while accepted != 0 {
5830            let internal_token = accepted.trailing_zeros();
5831            accepted &= accepted - 1;
5832            let Some(originals) = boundary
5833                .internal_token_to_originals
5834                .get(internal_token as usize)
5835            else {
5836                return false;
5837            };
5838            for &original in originals {
5839                let outer_internal = self
5840                    .constraint
5841                    .original_token_internal_at(original)
5842                    .unwrap_or(u32::MAX);
5843                if outer_internal != u32::MAX && dense_contains(allowed, outer_internal) {
5844                    set_original_mask_bit(buf, original);
5845                }
5846            }
5847        }
5848        true
5849    }
5850
5851    fn or_boundary_dag_via_shared_queue(
5852        &self,
5853        boundary: &crate::runtime::SegmentedBoundaryParser,
5854        parser_dwa: &crate::automata::weighted_u32::dwa::DWA,
5855        recursive_parser: bool,
5856        boundary_tsids: &[u32],
5857        global_tokenizer_state: u32,
5858        gss: &ParserGSS,
5859        top_live: &impl Fn(Option<u32>) -> bool,
5860        buf: &mut [u32],
5861    ) -> bool {
5862        let started = crate::env::var_os("GLRMASK_PROFILE_STATIC_BOUNDARY").is_some().then(Instant::now);
5863        let mut group_count = 0;
5864        for (stacks, accumulator) in gss.partition_by_accumulator() {
5865            group_count += 1;
5866            let Some(allowed) = self.terminals_disallowed_to_dense_acc(
5867                &accumulator, global_tokenizer_state,
5868            ) else { return false; };
5869            // Partition by exact exclusion accumulator BEFORE evaluation, so
5870            // accepted language and output eligibility remain correlated.
5871            // Partitioning operates on the compact GSS, never enumerating a
5872            // bounded list of individual stacks.
5873            let accepted = if !recursive_parser {
5874                if let Some(compact) = boundary.compact_parser_dwa.as_ref() {
5875                    boundary_mask64_via_shared_queue(compact, boundary_tsids[0], &stacks, top_live)
5876                } else {
5877                    boundary_weight_mask_via_shared_queue(parser_dwa, boundary_tsids,
5878                        boundary.internal_token_to_originals.len(), &stacks, top_live)
5879                }
5880            } else {
5881                boundary_weight_mask_via_shared_queue(parser_dwa, boundary_tsids,
5882                    boundary.internal_token_to_originals.len(), &stacks, top_live)
5883            };
5884            let Some(accepted) = accepted else { continue; };
5885            for (_, dense) in &accepted.0 {
5886                for (word, &bits) in dense.iter().enumerate() {
5887                    let mut bits = bits;
5888                    while bits != 0 {
5889                        let internal = word * 64 + bits.trailing_zeros() as usize;
5890                        bits &= bits - 1;
5891                        let Some(originals) = boundary.internal_token_to_originals.get(internal)
5892                            else { return false; };
5893                        for &original in originals {
5894                            let Some(outer_internal) = self.constraint.original_token_internal_at(original)
5895                                .filter(|&token| token != u32::MAX) else { continue; };
5896                            if allowed.0.iter().any(|(_, dense)| {
5897                                dense.get(outer_internal as usize / 64)
5898                                    .is_some_and(|word| word & (1u64 << (outer_internal % 64)) != 0)
5899                            }) { set_original_mask_bit(buf, original); }
5900                        }
5901                    }
5902                }
5903            }
5904        }
5905        if let Some(started) = started {
5906            eprintln!("[glrmask/profile][static_boundary_dag] backend=shared_queue groups={group_count} total_ns={} complete=true", elapsed_ns(started));
5907        }
5908        true
5909    }
5910
5911    /// Evaluate the private-coordinate deterministic boundary parser DWA over
5912    /// the current composed parser GSS.  The boundary machine is fully
5913    /// determinized and negative-free before publication; only the top-level
5914    /// union with the component parser DWA remains segmented at runtime.
5915    fn or_segmented_boundary_parser_mask(
5916        &self,
5917        boundary: &crate::runtime::SegmentedBoundaryParser,
5918        start_parser_states: Option<&crate::ds::bitset::BitSet>,
5919        start_component: Option<u32>,
5920        accepts_empty_stack: bool,
5921        buf: &mut [u32],
5922    ) -> bool {
5923        #[cfg(test)]
5924        fn reference_accepted_for_stack(
5925            dwa: &crate::automata::weighted_u32::dwa::DWA,
5926            top_first: &[u32],
5927        ) -> Weight {
5928            let mut ops = crate::ds::weight::ScopedWeightOpCache::default();
5929            let mut state_id = dwa.start_state();
5930            let mut path_weight = Weight::all();
5931            let mut accepted = Weight::empty();
5932            let accumulate_final = |state_id: u32,
5933                                    path_weight: &Weight,
5934                                    accepted: &mut Weight,
5935                                    ops: &mut crate::ds::weight::ScopedWeightOpCache| {
5936                if let Some(final_weight) = dwa
5937                    .states()
5938                    .get(state_id as usize)
5939                    .and_then(|state| state.final_weight.as_ref())
5940                {
5941                    let contribution = ops.intersection(path_weight, final_weight);
5942                    if !contribution.is_empty() {
5943                        *accepted = ops.union(accepted, &contribution);
5944                    }
5945                }
5946            };
5947            accumulate_final(state_id, &path_weight, &mut accepted, &mut ops);
5948
5949            for &parser_state in top_first {
5950                let label = encode_positive_label(parser_state);
5951                let Some(state) = dwa.states().get(state_id as usize) else {
5952                    break;
5953                };
5954                let Some((target, edge_weight)) = state
5955                    .transitions
5956                    .get(&label)
5957                    .or_else(|| state.transitions.get(&DEFAULT_LABEL))
5958                else {
5959                    break;
5960                };
5961                path_weight = ops.intersection(&path_weight, edge_weight);
5962                if path_weight.is_empty() {
5963                    break;
5964                }
5965                state_id = *target;
5966                accumulate_final(state_id, &path_weight, &mut accepted, &mut ops);
5967            }
5968            accepted
5969        }
5970
5971        fn accepted_dense_for_stack(
5972            dwa: &crate::automata::weighted_u32::dwa::DWA,
5973            tsid: u32,
5974            token_count: usize,
5975            top_first: &[u32],
5976        ) -> Vec<u64> {
5977            let mut path = vec![u64::MAX; token_count.div_ceil(64)];
5978            if !token_count.is_multiple_of(64) {
5979                *path.last_mut().expect("nonempty token universe") =
5980                    (1u64 << (token_count % 64)) - 1;
5981            }
5982            let mut accepted = vec![0; path.len()];
5983            let mut aux = Vec::new();
5984            // Boundary token IDs belong to this shard, not to the outer
5985            // constraint. Reuse the normal dense/range primitives but never
5986            // consult a cache keyed in the outer token coordinate.
5987            let precomputed = DenseTokenMaskCache::default();
5988            walk_single_stack::<false, _>(
5989                dwa.start_state(), top_first,
5990                |state| dwa.states().get(state as usize)?.final_weight.as_ref(),
5991                |state, parser| {
5992                    let row = &dwa.states().get(state as usize)?.transitions;
5993                    row.get(&encode_positive_label(parser))
5994                        .or_else(|| row.get(&DEFAULT_LABEL))
5995                        .map(|(target, weight)| (*target, weight))
5996                },
5997                |event| {
5998                    match event {
5999                        StackWalkEvent::Final(weight) => {
6000                            let weight = RuntimeWeightRef::Materialized(weight);
6001                            if weight.is_full() {
6002                                for (out, &bits) in accepted.iter_mut().zip(&path) {
6003                                    *out |= bits;
6004                                }
6005                            } else if let Some(tokens) = weight.token_set_for_tsid(tsid) {
6006                                DenseMaskAcc::or_dense_and_runtime_token_set_into(
6007                                    &path, tokens, &precomputed, &mut accepted,
6008                                );
6009                            }
6010                        }
6011                        StackWalkEvent::Intersect(weight) => {
6012                            return intersect_static_dense_with_weight(
6013                                &mut path, &mut aux, tsid,
6014                                RuntimeWeightRef::Materialized(weight), |_| None,
6015                            );
6016                        }
6017                        StackWalkEvent::Top(_) => unreachable!("top hook is compiled out"),
6018                    }
6019                    true
6020                },
6021            );
6022            #[cfg(test)]
6023            {
6024                // Independent pre-refactor symbolic walk: compare the whole
6025                // private mask before outer eligibility filtering can hide a
6026                // traversal, TSID, or padding error.
6027                let reference = reference_accepted_for_stack(dwa, top_first);
6028                let mut expected = vec![0u64; accepted.len()];
6029                for token in 0..token_count {
6030                    if reference.is_full() || reference.token_set_for_tsid_ref(tsid)
6031                        .is_some_and(|tokens| tokens.contains(token as u32))
6032                    {
6033                        expected[token / 64] |= 1u64 << (token % 64);
6034                    }
6035                }
6036                assert_eq!(accepted, expected, "boundary shared walk tsid={tsid} stack={top_first:?}");
6037            }
6038            accepted
6039        }
6040
6041        fn accepted_mask_for_stack(
6042            dwa: &crate::compiler::stages::parser_dwa::SmallBoundaryDwa,
6043            tsid: u32,
6044            top_first: &[u32],
6045        ) -> u64 {
6046            if tsid >= dwa.tsid_count as u32 {
6047                return 0;
6048            }
6049            let mut path_mask = dwa.all_token_mask();
6050            let mut accepted = 0u64;
6051            walk_single_stack::<false, _>(
6052                dwa.start_state(), top_first,
6053                |state| {
6054                    let weight = dwa.states.get(state as usize)?.final_weight;
6055                    (weight != 0).then(|| dwa.weight_mask(weight, tsid))
6056                },
6057                |state, parser| {
6058                    let row = &dwa.states.get(state as usize)?.transitions;
6059                    let label = encode_positive_label(parser);
6060                    row.iter().find(|(key, _, _)| *key == label)
6061                        .or_else(|| row.iter().find(|(key, _, _)| *key == DEFAULT_LABEL))
6062                        .map(|&(_, target, weight)| (target, dwa.weight_mask(weight, tsid)))
6063                },
6064                |event| {
6065                    match event {
6066                        StackWalkEvent::Final(weight) => accepted |= path_mask & weight,
6067                        StackWalkEvent::Intersect(weight) => {
6068                            path_mask &= weight;
6069                            return path_mask != 0;
6070                        }
6071                        StackWalkEvent::Top(_) => unreachable!("top hook is compiled out"),
6072                    }
6073                    true
6074                },
6075            );
6076            accepted
6077        }
6078
6079        fn dense_contains(acc: &DenseMaskAcc, token: u32) -> bool {
6080            let word = token as usize / 64;
6081            let bit = token % 64;
6082            acc.0.iter().any(|(_, dense)| {
6083                dense.get(word)
6084                    .is_some_and(|word_value| (*word_value & (1u64 << bit)) != 0)
6085            })
6086        }
6087
6088        let recursive_parser = self.constraint.uses_compact_segmented_parser_runtime();
6089        let parser_dwa = if recursive_parser {
6090            boundary
6091                .recursive_parser_dwa
6092                .as_ref()
6093                .unwrap_or(&boundary.parser_dwa)
6094        } else {
6095            &boundary.parser_dwa
6096        };
6097        let debug_boundary = crate::env::var_os("GLRMASK_DEBUG_SEGMENTED_BOUNDARY_MASK").is_some();
6098        for (&global_tokenizer_state, gss) in self.state.iter() {
6099            let boundary_tsids = if recursive_parser && boundary.uses_composed_tsid_coordinate {
6100                self.constraint
6101                    .runtime_internal_tsids_for_tokenizer_state(global_tokenizer_state)
6102                    .unwrap_or_default()
6103            } else if boundary.uses_composed_tsid_coordinate {
6104                self.constraint
6105                    .state_to_internal_tsid
6106                    .get(global_tokenizer_state as usize)
6107                    .copied()
6108                    .filter(|&tsid| tsid != u32::MAX)
6109                    .into_iter()
6110                    .collect::<SmallVec<[u32; 4]>>()
6111            } else {
6112                boundary
6113                    .tokenizer_state_to_tsid
6114                    .get(global_tokenizer_state as usize)
6115                    .copied()
6116                    .filter(|&tsid| tsid != u32::MAX)
6117                    .into_iter()
6118                    .collect::<SmallVec<[u32; 4]>>()
6119            };
6120            if debug_boundary {
6121                eprintln!(
6122                    "[glrmask/debug][segmented_boundary_state] global_tokenizer_state={} boundary_tsids={:?} paths={}",
6123                    global_tokenizer_state,
6124                    boundary_tsids,
6125                    gss.path_count_at_most(129),
6126                );
6127            }
6128            if boundary_tsids.is_empty() {
6129                continue;
6130            }
6131            let mut complete = true;
6132            // Cap-free exact evaluation: single-path GSSes keep the direct
6133            // per-stack walk (exactly one path, so the bound can never bite),
6134            // while ambiguous GSSes run the memoized DAG x DWA product
6135            // evaluator so >128 / shared-tail path counts stay exact with no
6136            // decline and no hidden dynamic fallback.
6137            let traversal_complete = if gss.is_single_path() {
6138                // Isolated static-boundary profiling (Priority 4): single-path
6139                // evaluations dominate ordinary states; time them separately
6140                // from DynamicDirect and commits.
6141                let single_started =
6142                    crate::env::var_os("GLRMASK_PROFILE_STATIC_BOUNDARY").is_some().then(Instant::now);
6143                let mut single_paths = 0usize;
6144                // Phase breakdown for hotspot attribution on slow evaluations
6145                // (allowed = exclusion accumulator projection, walk = DWA
6146                // product walk, admit = internal->original mapping/filter).
6147                let mut phase_allowed_ns: u64 = 0;
6148                let mut phase_walk_ns: u64 = 0;
6149                let mut phase_admit_ns: u64 = 0;
6150                let mut single_depth = 0usize;
6151                let complete_single = gss.for_each_stack_top_first_bounded(128, |top_first, acc| {
6152                    single_paths += 1;
6153                    single_depth = single_depth.max(top_first.len());
6154                if recursive_parser {
6155                    if let Some(start_component) = start_component {
6156                        match top_first.first().copied() {
6157                            Some(top)
6158                                if self
6159                                    .constraint
6160                                    .compact_segmented_parser_component(top).is_none_or(|(owner, _)| owner != start_component as usize) =>
6161                            {
6162                                return;
6163                            }
6164                            None if !accepts_empty_stack => return,
6165                            _ => {}
6166                        }
6167                    }
6168                } else if let Some(start_parser_states) = start_parser_states {
6169                    match top_first.first().copied() {
6170                        Some(top) if !start_parser_states.contains(top as usize) => return,
6171                        None if !accepts_empty_stack => return,
6172                        _ => {}
6173                    }
6174                }
6175                let phase_mark = single_started.is_some().then(Instant::now);
6176                let Some(allowed) =
6177                    self.terminals_disallowed_to_dense_acc(acc, global_tokenizer_state)
6178                else {
6179                    // This segmented evaluator is an optimization. If an
6180                    // exclusion accumulator cannot be represented exactly in
6181                    // its dense scratch form, decline the whole projection so
6182                    // the caller runs the unified exact fallback.
6183                    complete = false;
6184                    return;
6185                };
6186                if let Some(mark) = phase_mark {
6187                    phase_allowed_ns += elapsed_ns(mark);
6188                }
6189                if !recursive_parser
6190                    && let Some(compact) = boundary.compact_parser_dwa.as_ref()
6191                {
6192                    let boundary_tsid = boundary_tsids[0];
6193                    let walk_mark = single_started.is_some().then(Instant::now);
6194                    let mut accepted = accepted_mask_for_stack(compact, boundary_tsid, top_first);
6195                    if let Some(mark) = walk_mark {
6196                        phase_walk_ns += elapsed_ns(mark);
6197                    }
6198                    if debug_boundary {
6199                        let internal = (0..compact.token_count as u32)
6200                            .filter(|&token| accepted & (1u64 << token) != 0)
6201                            .collect::<Vec<_>>();
6202                        let originals = internal
6203                            .iter()
6204                            .flat_map(|&token| boundary.internal_token_to_originals.get(token as usize).into_iter().flatten().copied())
6205                            .collect::<Vec<_>>();
6206                        eprintln!(
6207                            "[glrmask/debug][segmented_boundary_stack] top_first={:?} tsid={} accepted_internal={:?} accepted_originals={:?} compact=true",
6208                            top_first,
6209                            boundary_tsid,
6210                            internal,
6211                            originals,
6212                        );
6213                    }
6214                    let admit_mark = single_started.is_some().then(Instant::now);
6215                    while accepted != 0 {
6216                        let internal_token = accepted.trailing_zeros();
6217                        accepted &= accepted - 1;
6218                        let Some(originals) = boundary
6219                            .internal_token_to_originals
6220                            .get(internal_token as usize)
6221                        else {
6222                            complete = false;
6223                            return;
6224                        };
6225                        for &original in originals {
6226                            let outer_internal = self
6227                                .constraint
6228                                .original_token_internal_at(original)
6229                                .unwrap_or(u32::MAX);
6230                            if outer_internal != u32::MAX && dense_contains(&allowed, outer_internal) {
6231                                set_original_mask_bit(buf, original);
6232                            }
6233                        }
6234                    }
6235                    if let Some(mark) = admit_mark {
6236                        phase_admit_ns += elapsed_ns(mark);
6237                    }
6238                } else {
6239                    let mut debug_internal = Vec::new();
6240                    let mut debug_originals = Vec::new();
6241                    for &boundary_tsid in &boundary_tsids {
6242                        let walk_mark = single_started.is_some().then(Instant::now);
6243                        let accepted = accepted_dense_for_stack(
6244                            parser_dwa, boundary_tsid,
6245                            boundary.internal_token_to_originals.len(), top_first,
6246                        );
6247                        if let Some(mark) = walk_mark {
6248                            phase_walk_ns += elapsed_ns(mark);
6249                        }
6250                        let admit_mark = single_started.is_some().then(Instant::now);
6251                        for (word_index, mut bits) in accepted.into_iter().enumerate() {
6252                            while bits != 0 {
6253                                let internal_token = (word_index * 64) as u32 + bits.trailing_zeros();
6254                                bits &= bits - 1;
6255                                let Some(originals) = boundary
6256                                    .internal_token_to_originals
6257                                    .get(internal_token as usize)
6258                                else {
6259                                    complete = false;
6260                                    return;
6261                                };
6262                                if debug_boundary {
6263                                    debug_internal.push(internal_token);
6264                                    debug_originals.extend_from_slice(originals);
6265                                }
6266                                for &original in originals {
6267                                    let outer_internal = self
6268                                        .constraint
6269                                        .original_token_internal_at(original)
6270                                        .unwrap_or(u32::MAX);
6271                                    if outer_internal != u32::MAX
6272                                        && dense_contains(&allowed, outer_internal)
6273                                    {
6274                                        set_original_mask_bit(buf, original);
6275                                    }
6276                                }
6277                            }
6278                        }
6279                        if let Some(mark) = admit_mark {
6280                            phase_admit_ns += elapsed_ns(mark);
6281                        }
6282                    }
6283                    if debug_boundary {
6284                        debug_internal.sort_unstable();
6285                        debug_internal.dedup();
6286                        debug_originals.sort_unstable();
6287                        debug_originals.dedup();
6288                        eprintln!(
6289                            "[glrmask/debug][segmented_boundary_stack] top_first={:?} tsids={:?} accepted_internal={:?} accepted_originals={:?}",
6290                            top_first,
6291                            boundary_tsids,
6292                            debug_internal,
6293                            debug_originals,
6294                        );
6295                    }
6296                }
6297                });
6298                if let Some(single_started) = single_started {
6299                    let total_ns = elapsed_ns(single_started);
6300                    eprintln!(
6301                        "[glrmask/profile][static_boundary_dag] gss_nodes=0 upper_memo=0 lower_memo=0 groups=0 dwa_steps=0 weight_unions=0 weight_intersections=0 total_ns={total_ns} complete={complete} compact=single paths={single_paths} depth={single_depth} allowed_ns={phase_allowed_ns} walk_ns={phase_walk_ns} admit_ns={phase_admit_ns}",
6302                    );
6303                }
6304                complete_single
6305            } else {
6306                // Exact memoized DAG x DWA product evaluation (no path cap).
6307                // Groups preserve the per-path eligibility correlation:
6308                // union over groups of (accepted(group) intersect
6309                // eligible(group)), never union-accepts independently of
6310                // union-eligibility.
6311                let top_live = |top: Option<u32>| -> bool {
6312                    if recursive_parser {
6313                        if let Some(start_component) = start_component {
6314                            match top {
6315                                Some(value) => self
6316                                    .constraint
6317                                    .compact_segmented_parser_component(value)
6318                                    .is_some_and(|(owner, _)| owner == start_component as usize),
6319                                None => accepts_empty_stack,
6320                            }
6321                        } else {
6322                            true
6323                        }
6324                    } else if let Some(start_parser_states) = start_parser_states {
6325                        match top {
6326                            Some(value) => start_parser_states.contains(value as usize),
6327                            None => accepts_empty_stack,
6328                        }
6329                    } else {
6330                        true
6331                    }
6332                };
6333                #[cfg(test)]
6334                let mut reference_mask = buf.to_vec();
6335                let shared_complete = self.or_boundary_dag_via_shared_queue(
6336                    boundary, parser_dwa, recursive_parser, &boundary_tsids,
6337                    global_tokenizer_state, gss, &top_live, buf,
6338                );
6339                #[cfg(test)]
6340                {
6341                let buf = reference_mask.as_mut_slice();
6342                let mut complete = true;
6343                let dag = gss.indexed_dag();
6344                let profile_static =
6345                    crate::env::var_os("GLRMASK_PROFILE_STATIC_BOUNDARY").is_some();
6346                let dag_started = profile_static.then(Instant::now);
6347                if !recursive_parser
6348                    && let Some(compact) = boundary.compact_parser_dwa.as_ref()
6349                {
6350                    let boundary_tsid = boundary_tsids[0];
6351                    let mut evaluator =
6352                        BoundaryMask64DagEvaluator::new(compact, boundary_tsid, &dag);
6353                    let groups = evaluator.eval_root(&top_live);
6354                    for (group, accepted) in &groups {
6355                        let Some(acc) = evaluator.group_accumulator(*group) else {
6356                            complete = false;
6357                            break;
6358                        };
6359                        let Some(allowed) = self.terminals_disallowed_to_dense_acc(
6360                            &acc,
6361                            global_tokenizer_state,
6362                        ) else {
6363                            complete = false;
6364                            break;
6365                        };
6366                        if !self.admit_boundary_mask64_group(boundary, *accepted, &allowed, buf)
6367                        {
6368                            complete = false;
6369                            break;
6370                        }
6371                    }
6372                    if let Some(dag_started) = dag_started {
6373                        eprintln!(
6374                            "[glrmask/profile][static_boundary_dag] gss_nodes={} upper_memo={} lower_memo={} groups={} dwa_steps={} total_ns={} complete={complete} compact=true",
6375                            dag.nodes.len(),
6376                            evaluator.upper_memo.len(),
6377                            evaluator.lower_memo.len(),
6378                            groups.len(),
6379                            evaluator.dwa_steps,
6380                            elapsed_ns(dag_started),
6381                        );
6382                    }
6383                } else {
6384                    let mut evaluator = BoundaryWeightDagEvaluator::new(parser_dwa, &dag);
6385                    let groups = evaluator.eval_root(&top_live);
6386                    for (group, accepted) in &groups {
6387                        let Some(acc) = evaluator.group_accumulator(*group) else {
6388                            complete = false;
6389                            break;
6390                        };
6391                        let Some(allowed) = self.terminals_disallowed_to_dense_acc(
6392                            &acc,
6393                            global_tokenizer_state,
6394                        ) else {
6395                            complete = false;
6396                            break;
6397                        };
6398                        if !self.admit_boundary_weight_group(
6399                            boundary,
6400                            accepted,
6401                            &boundary_tsids,
6402                            &allowed,
6403                            buf,
6404                        ) {
6405                            complete = false;
6406                            break;
6407                        }
6408                    }
6409                    if let Some(dag_started) = dag_started {
6410                        eprintln!(
6411                            "[glrmask/profile][static_boundary_dag] gss_nodes={} upper_memo={} lower_memo={} groups={} dwa_steps={} weight_unions={} weight_intersections={} total_ns={} complete={complete} compact=false",
6412                            dag.nodes.len(),
6413                            evaluator.upper_memo.len(),
6414                            evaluator.lower_memo.len(),
6415                            groups.len(),
6416                            evaluator.dwa_steps,
6417                            evaluator.weight_unions,
6418                            evaluator.weight_intersections,
6419                            elapsed_ns(dag_started),
6420                        );
6421                    }
6422                }
6423                assert_eq!(shared_complete, complete, "shared boundary queue completeness differs from DAG oracle");
6424                }
6425                #[cfg(test)]
6426                if shared_complete {
6427                    assert_eq!(buf, reference_mask.as_slice(), "shared boundary queue mask differs from exact DAG oracle");
6428                }
6429                shared_complete
6430            };
6431            if !traversal_complete || !complete {
6432                return false;
6433            }
6434        }
6435        true
6436    }
6437
6438    /// Two-DWA runtime: the ordinary mask hot path evaluates deterministic A
6439    /// (`constraint.parser_dwa`) first, then ORs deterministic boundary DWA B.
6440    /// The legacy segmented-component experiment already evaluates B inside its
6441    /// own path, so only apply this overlay when there are no component
6442    /// segments.
6443    fn or_two_dwa_boundary_parser_mask(&self, buf: &mut [u32]) -> bool {
6444        let Some(overlay) = self.constraint.static_dynamic_overlay.as_ref() else {
6445            return true;
6446        };
6447        if !overlay.segmented_parser_components.is_empty() {
6448            return true;
6449        }
6450        if !self.or_segmented_boundary_shards_mask(overlay, buf) {
6451            return false;
6452        }
6453        true
6454    }
6455
6456    /// Exact overlay for an out-of-vocabulary special token reached only after
6457    /// a linker control chain. Ordinary parser-DWA weights remain the fast path;
6458    /// constraints without explicit controls pay nothing here.
6459    fn update_control_special_token_mask(&self, buf: &mut [u32]) {
6460        if self.constraint.special_token_terminals.is_empty() { return; }
6461        // A data-only constructor's static byte DWA deliberately has no exact
6462        // token edges. Query the same complete parser relation for those IDs;
6463        // exact-only tokens must never be reinterpreted as their vocabulary bytes.
6464        if !self.constraint.parser_has_controls()
6465            && !self.constraint.uses_compact_segmented_parser_runtime()
6466            && !self.constraint.has_template_parser()
6467        {
6468            return;
6469        }
6470        for special in &self.constraint.special_token_terminals {
6471            if self.constraint.is_late_grammar_placeholder_terminal(special.terminal_id) { continue; }
6472            if super::commit::advance_special_terminal_paths(
6473                &self.constraint, &self.state, special.terminal_id,
6474            ).is_some_and(|gss| !gss.is_empty()) {
6475                special.or_mask(buf);
6476            }
6477        }
6478    }
6479
6480    pub(crate) fn clear_late_grammar_placeholder_mask(&self, buf: &mut [u32]) {
6481        for special in &self.constraint.special_token_terminals {
6482            if !self
6483                .constraint
6484                .is_late_grammar_placeholder_terminal(special.terminal_id)
6485            {
6486                continue;
6487            }
6488            let word = special.token_id as usize / 32;
6489            let bit = special.token_id % 32;
6490            if let Some(slot) = buf.get_mut(word) {
6491                *slot &= !(1u32 << bit);
6492            }
6493        }
6494        self.enforce_empty_byte_token_domain(buf);
6495    }
6496
6497    /// A zero-byte model ID is not an ordinary byte transition. Enforce the
6498    /// shared commit endpoint policy at final output, retaining an
6499    /// empty-spelled special ID only via its exact live action. Root end IDs
6500    /// are applied separately after this body-domain filter.
6501    fn enforce_empty_byte_token_domain(&self, buf: &mut [u32]) {
6502        if self.constraint.empty_byte_token_ids.is_empty()
6503            || !(self.constraint.has_template_parser()
6504                || self.constraint.uses_dynamic_runtime()
6505                || self.constraint.uses_compact_segmented_parser_runtime())
6506        { return; }
6507        // Liveness belongs to a parser terminal, not to every token in its
6508        // interval. In particular, an all-vocabulary empty-spelled binding must
6509        // not perform one parser advance per model ID. This inventory is sorted
6510        // and unique, whether prepared from Vocab or reconstructed during load.
6511        let empty_ids = self.constraint.empty_byte_token_ids.as_ref();
6512        let mut live_ranges = smallvec::SmallVec::<[(u32, u32); 8]>::new();
6513        for special in &self.constraint.special_token_terminals {
6514            if self.constraint.is_late_grammar_placeholder_terminal(special.terminal_id) {
6515                continue;
6516            }
6517            let first_empty = empty_ids.partition_point(|&id| id < special.token_id);
6518            if empty_ids.get(first_empty).is_none_or(|&id| id > special.token_id_end) {
6519                continue;
6520            }
6521            if super::commit::advance_special_terminal_paths(
6522                &self.constraint, &self.state, special.terminal_id,
6523            ).is_some_and(|stack| !stack.is_empty()) {
6524                live_ranges.push((special.token_id, special.token_id_end));
6525            }
6526        }
6527        retain_live_empty_byte_ranges(buf, empty_ids, &mut live_ranges);
6528    }
6529
6530    fn fill_blocked_seed_dense(
6531        &self,
6532        terminals_disallowed: &TerminalsDisallowed,
6533        blocked: &mut Vec<u64>,
6534    ) {
6535        const MAX_FALLBACK_MASKS: usize = 512;
6536
6537        let profile = crate::env::var_os("GLRMASK_PROFILE_SEED_EXCLUSIONS").is_some();
6538        let started = profile.then(Instant::now);
6539        blocked.clear();
6540        blocked.resize(self.constraint.seed_universe_dense.len(), 0);
6541        if terminals_disallowed.is_empty() {
6542            return;
6543        }
6544
6545        let mut missing_pairs = SmallVec::<[(u32, TerminalID); 4]>::new();
6546        for (&continuation_tokenizer_state, terminals) in terminals_disallowed.iter() {
6547            let exclusion_state = self.constraint.static_exclusion_state(continuation_tokenizer_state)
6548                .expect("validated recursive lexer state must have a static observation");
6549            for &terminal_id in terminals.iter() {
6550                if let Some(mask) = self
6551                    .constraint
6552                    .seed_terminal_dense
6553                    .get(&(exclusion_state, terminal_id))
6554                {
6555                    for (blocked_word, mask_word) in blocked.iter_mut().zip(mask.iter()) {
6556                        *blocked_word |= mask_word;
6557                    }
6558                } else if !self.constraint.possible_matches_complete {
6559                    // IMPORTANT: this is a legacy-only escape hatch. The
6560                    // dynamic possible-matches fallback is terrible and will
6561                    // be removed. New compiler paths MUST provide complete
6562                    // exact possible matches instead of reaching this branch.
6563                    // DO NOT REMOVE OR WEAKEN THIS COMMENT.
6564                    missing_pairs.push((continuation_tokenizer_state, terminal_id));
6565                }
6566            }
6567        }
6568
6569        let mut cache_hits = 0usize;
6570        let mut uncached = SmallVec::<[(u32, TerminalID); 4]>::new();
6571        if !missing_pairs.is_empty() {
6572            let cache = self
6573                .constraint
6574                .seed_terminal_dense_fallback
6575                .lock()
6576                .expect("seed exclusion cache poisoned");
6577            for &pair in &missing_pairs {
6578                if let Some(mask) = cache.get(&pair) {
6579                    cache_hits += 1;
6580                    for (blocked_word, mask_word) in blocked.iter_mut().zip(mask.iter()) {
6581                        *blocked_word |= mask_word;
6582                    }
6583                } else if !uncached.contains(&pair) {
6584                    uncached.push(pair);
6585                }
6586            }
6587        }
6588
6589        let dynamic_started = profile.then(Instant::now);
6590        for (continuation_tokenizer_state, terminal_id) in uncached.iter().copied() {
6591            let exclusions = TerminalsDisallowed::new()
6592                .with_insert(continuation_tokenizer_state, terminal_id);
6593            let mut computed = vec![0u64; blocked.len()];
6594            super::dynamic_mask::or_blocked_internal_tokens_for_exclusions(
6595                &self.constraint,
6596                &exclusions,
6597                &mut computed,
6598            )
6599            .expect("unbounded seed-exclusion scan cannot fail");
6600            let computed: Arc<[u64]> = computed.into();
6601
6602            let selected = {
6603                let mut cache = self
6604                    .constraint
6605                    .seed_terminal_dense_fallback
6606                    .lock()
6607                    .expect("seed exclusion cache poisoned");
6608                if let Some(existing) = cache.get(&(continuation_tokenizer_state, terminal_id)) {
6609                    Arc::clone(existing)
6610                } else {
6611                    if cache.len() < MAX_FALLBACK_MASKS {
6612                        cache.insert(
6613                            (continuation_tokenizer_state, terminal_id),
6614                            Arc::clone(&computed),
6615                        );
6616                    }
6617                    computed
6618                }
6619            };
6620            for (blocked_word, mask_word) in blocked.iter_mut().zip(selected.iter()) {
6621                *blocked_word |= mask_word;
6622            }
6623        }
6624
6625        if let Some(started) = started {
6626            eprintln!(
6627                "[glrmask/profile][seed_exclusions] total_ns={} dynamic_ns={} remembered_pairs={} fallback_pairs={} cache_hits={} computed_pairs={} missing={:?}",
6628                elapsed_ns(started),
6629                dynamic_started.map(elapsed_ns).unwrap_or(0),
6630                terminals_disallowed
6631                    .iter()
6632                    .map(|(_, terminals)| terminals.len())
6633                    .sum::<usize>(),
6634                missing_pairs.len(),
6635                cache_hits,
6636                uncached.len(),
6637                missing_pairs,
6638            );
6639        }
6640    }
6641
6642    fn try_fill_mask_single_path_direct(&self, buf: &mut [u32]) -> bool {
6643        if mask_inner_profile_enabled() || mask_delta_profile_enabled() {
6644            return false;
6645        }
6646
6647        if self.state.is_empty()
6648            || self.state.len() > MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_PATHS
6649        {
6650            return false;
6651        }
6652
6653        let mut paths = SmallVec::<[(u32, TerminalsDisallowed, SmallVec<[u32; MASK_SINGLE_PATH_DIRECT_INLINE_STACK_DEPTH]>); MASK_SINGLE_PATH_DIRECT_INLINE_PATH_CAPACITY]>::new();
6654        if self.state.len() < MASK_SINGLE_PATH_DIRECT_TWO_PASS_MIN_STATE_COUNT {
6655            // Below half the path budget, accepted multipath states are common
6656            // and a separate counting traversal costs more than it saves. Keep
6657            // the original one-pass admission/materialization algorithm.
6658            for (&original_tokenizer_state, gss) in &self.state {
6659                if gss.max_depth() > MASK_SINGLE_PATH_DIRECT_MAX_DEPTH {
6660                    return false;
6661                }
6662
6663                let mut stack = SmallVec::<[u32; MASK_SINGLE_PATH_DIRECT_INLINE_STACK_DEPTH]>::new();
6664                if let Some(terminals_disallowed) = gss.single_path_top_first_and_acc(&mut stack) {
6665                    paths.push((original_tokenizer_state, terminals_disallowed, stack));
6666                    continue;
6667                }
6668
6669                if mask_single_path_to_stacks_fallback_disabled() {
6670                    return false;
6671                }
6672                let remaining = MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_PATHS
6673                    .saturating_sub(paths.len())
6674                    .min(MASK_SINGLE_PATH_DIRECT_MAX_PATHS_PER_GSS);
6675                let complete = gss.for_each_stack_top_first_bounded(
6676                    remaining,
6677                    |stack_top_first, terminals_disallowed| {
6678                        let mut path_stack = SmallVec::<[u32; MASK_SINGLE_PATH_DIRECT_INLINE_STACK_DEPTH]>::new();
6679                        path_stack.extend(stack_top_first.iter().copied());
6680                        paths.push((
6681                            original_tokenizer_state,
6682                            terminals_disallowed.clone(),
6683                            path_stack,
6684                        ));
6685                    },
6686                );
6687                if !complete {
6688                    return false;
6689                }
6690            }
6691        } else {
6692            // Once active tokenizer states consume at least half the path
6693            // budget, a small amount of branching is likely to reject the
6694            // specialized kernel. Count without cloning stack values first;
6695            // only accepted states pay to materialize concrete stacks.
6696            let mut all_single_path = true;
6697            for (&original_tokenizer_state, gss) in &self.state {
6698                if gss.max_depth() > MASK_SINGLE_PATH_DIRECT_MAX_DEPTH {
6699                    return false;
6700                }
6701
6702                let mut stack = SmallVec::<[u32; MASK_SINGLE_PATH_DIRECT_INLINE_STACK_DEPTH]>::new();
6703                let Some(terminals_disallowed) = gss.single_path_top_first_and_acc(&mut stack) else {
6704                    all_single_path = false;
6705                    break;
6706                };
6707                paths.push((original_tokenizer_state, terminals_disallowed, stack));
6708            }
6709
6710            if !all_single_path {
6711                if mask_single_path_to_stacks_fallback_disabled() {
6712                    return false;
6713                }
6714
6715                let mut total_paths = 0usize;
6716                let mut total_stack_values = 0usize;
6717                for gss in self.state.values() {
6718                    if gss.max_depth() > MASK_SINGLE_PATH_DIRECT_MAX_DEPTH {
6719                        return false;
6720                    }
6721                    let remaining = MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_PATHS
6722                        .saturating_sub(total_paths)
6723                        .min(MASK_SINGLE_PATH_DIRECT_MAX_PATHS_PER_GSS);
6724                    let complete = gss.for_each_stack_len_bounded(remaining, |stack_len, _| {
6725                        total_paths += 1;
6726                        total_stack_values = total_stack_values.saturating_add(stack_len);
6727                    });
6728                    if !complete
6729                        || total_stack_values > MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_STACK_VALUES
6730                    {
6731                        return false;
6732                    }
6733                }
6734
6735                paths.clear();
6736                for (&original_tokenizer_state, gss) in &self.state {
6737                    let remaining = MASK_SINGLE_PATH_DIRECT_MAX_TOTAL_PATHS
6738                        .saturating_sub(paths.len())
6739                        .min(MASK_SINGLE_PATH_DIRECT_MAX_PATHS_PER_GSS);
6740                    let complete = gss.for_each_stack_top_first_bounded(
6741                        remaining,
6742                        |stack_top_first, terminals_disallowed| {
6743                            let mut path_stack = SmallVec::<[u32; MASK_SINGLE_PATH_DIRECT_INLINE_STACK_DEPTH]>::new();
6744                            path_stack.extend(stack_top_first.iter().copied());
6745                            paths.push((
6746                                original_tokenizer_state,
6747                                terminals_disallowed.clone(),
6748                                path_stack,
6749                            ));
6750                        },
6751                    );
6752                    debug_assert!(
6753                        complete,
6754                        "admitted GSS must materialize within the path budget"
6755                    );
6756                    if !complete {
6757                        return false;
6758                    }
6759                }
6760            }
6761        }
6762        if paths.iter().any(|(tokenizer_state, _, _)| {
6763            self.constraint
6764                .internal_tsids_for_state(*tokenizer_state)
6765                .len()
6766                != 1
6767        }) {
6768            return false;
6769        }
6770        let Some(total_stack_values) =
6771            single_path_direct_stack_work(paths.iter().map(|(_, _, stack)| stack.len()))
6772        else {
6773            return false;
6774        };
6775        if self.constraint.runtime_parser_dwa_state_count() == 0 {
6776            return false;
6777        }
6778
6779        let mut plan_ops =
6780            SmallVec::<[SinglePathDirectPlanOp<'_>; MASK_SINGLE_PATH_DIRECT_MAX_PLAN_OPS]>::new();
6781        let mut stack_plans = SmallVec::<
6782            [SinglePathDirectStackPlan; MASK_SINGLE_PATH_DIRECT_INLINE_PATH_CAPACITY],
6783        >::new();
6784        let mut path_plan_indices =
6785            SmallVec::<[u8; MASK_SINGLE_PATH_DIRECT_INLINE_PATH_CAPACITY]>::new();
6786        let mut repeated_stack_values = 0usize;
6787
6788        // Planning pays only when repeated parser-stack traversal dominates the
6789        // unique work.  This replaces the old 32-path switch with a direct cost
6790        // comparison: three copies of one deep stack can qualify, while 64
6791        // unrelated stacks do not build programs merely because the frontier is
6792        // wide.  First group stacks without touching the parser DWA; compile
6793        // programs only after the reuse test succeeds.
6794        if paths.len() >= 3 {
6795            for (path_index, (_, _, stack)) in paths.iter().enumerate() {
6796                let stack_fingerprint = single_path_direct_stack_fingerprint(stack);
6797                let existing = stack_plans.iter().position(|plan| {
6798                    plan.stack_fingerprint == stack_fingerprint
6799                        && paths[plan.representative_path].2.as_slice() == stack.as_slice()
6800                });
6801                let plan_index = if let Some(existing) = existing {
6802                    repeated_stack_values = repeated_stack_values.saturating_add(stack.len());
6803                    existing
6804                } else {
6805                    let plan_index = stack_plans.len();
6806                    stack_plans.push(SinglePathDirectStackPlan {
6807                        representative_path: path_index,
6808                        stack_fingerprint,
6809                        ops_start: 0,
6810                        ops_end: 0,
6811                    });
6812                    plan_index
6813                };
6814                path_plan_indices.push(plan_index as u8);
6815            }
6816        }
6817
6818        let should_build_stack_plans = path_plan_indices.len() == paths.len()
6819            && single_path_direct_plan_reuse_dominates(
6820                paths.len(),
6821                total_stack_values,
6822                repeated_stack_values,
6823            );
6824        let mut plans_complete = should_build_stack_plans;
6825        if should_build_stack_plans {
6826            'build_plans: for plan_index in 0..stack_plans.len() {
6827                let representative_path = stack_plans[plan_index].representative_path;
6828                let stack = &paths[representative_path].2;
6829                let ops_start = plan_ops.len();
6830                walk_single_stack::<true, _>(
6831                    self.constraint.runtime_parser_dwa_start_state(),
6832                    stack,
6833                    |state| self.constraint.runtime_parser_dwa_final_weight(state),
6834                    |state, parser| self.constraint.runtime_parser_dwa_transition(state, parser),
6835                    |event| {
6836                        match event {
6837                            StackWalkEvent::Final(final_weight) => {
6838                                if plan_ops.len() == MASK_SINGLE_PATH_DIRECT_MAX_PLAN_OPS {
6839                                    plans_complete = false;
6840                                    return false;
6841                                }
6842                                plan_ops.push(SinglePathDirectPlanOp::Merge(final_weight));
6843                                // Every continuation only intersects this
6844                                // path's candidate set. Full acceptance has
6845                                // already emitted that entire set.
6846                                if final_weight.is_full() {
6847                                    return false;
6848                                }
6849                            }
6850                            StackWalkEvent::Top(parser_state) => {
6851                                let positive_label = encode_positive_label(parser_state);
6852                                let has_direct_regular_acceptance = self
6853                                    .constraint
6854                                    .direct_regular_wide_acceptance_for_parser_state(parser_state)
6855                                    .is_some()
6856                                    || self
6857                                        .constraint
6858                                        .for_each_direct_regular_l1_acceptance(parser_state, |_| {});
6859                                if has_direct_regular_acceptance {
6860                                    plans_complete = false;
6861                                    return false;
6862                                }
6863                                if let Some(accept_weight) =
6864                                    self.constraint.runtime_parser_top_accept(positive_label)
6865                                {
6866                                    if plan_ops.len() == MASK_SINGLE_PATH_DIRECT_MAX_PLAN_OPS {
6867                                        plans_complete = false;
6868                                        return false;
6869                                    }
6870                                    plan_ops.push(SinglePathDirectPlanOp::Merge(accept_weight));
6871                                }
6872                                let accept_parts =
6873                                    self.constraint.runtime_parser_top_accept_parts(positive_label);
6874                                if !accept_parts.is_empty() {
6875                                    for accept_weight in accept_parts {
6876                                        if plan_ops.len() == MASK_SINGLE_PATH_DIRECT_MAX_PLAN_OPS {
6877                                            plans_complete = false;
6878                                            return false;
6879                                        }
6880                                        plan_ops.push(SinglePathDirectPlanOp::Merge(accept_weight));
6881                                    }
6882                                }
6883                            }
6884                            StackWalkEvent::Intersect(weight) => {
6885                                if plan_ops.len() == MASK_SINGLE_PATH_DIRECT_MAX_PLAN_OPS {
6886                                    plans_complete = false;
6887                                    return false;
6888                                }
6889                                plan_ops.push(SinglePathDirectPlanOp::Intersect(weight));
6890                            }
6891                        }
6892                        true
6893                    },
6894                );
6895                if !plans_complete {
6896                    break 'build_plans;
6897                }
6898
6899                stack_plans[plan_index].ops_start = ops_start;
6900                stack_plans[plan_index].ops_end = plan_ops.len();
6901            }
6902        }
6903        let use_stack_plans = plans_complete && should_build_stack_plans;
6904        buf.fill(0);
6905
6906        let precomputed = &self.constraint.weight_token_dense_masks;
6907        let dense_words = self.constraint.internal_token_dense_words;
6908        let mut scratch = mask_scratch(&self.constraint);
6909        let (mut merged, mut output_scratch, mut single_path_aux, mut single_path_acc) = {
6910            (
6911                std::mem::take(&mut scratch.merged_dense),
6912                std::mem::take(&mut scratch.output_buf),
6913                std::mem::take(&mut scratch.single_path_aux_dense),
6914                std::mem::take(&mut scratch.single_path_acc_dense),
6915            )
6916        };
6917        merged.clear();
6918        merged.resize(dense_words, 0);
6919        let mut used_direct_final = false;
6920        let mut direct_buf_dirty = false;
6921
6922        let mut restore_scratch = |
6923            merged: Vec<u64>,
6924            output_scratch: Vec<u32>,
6925            single_path_aux: Vec<u64>,
6926            single_path_acc: Vec<u64>,
6927        | {
6928            scratch.merged_dense = merged;
6929            scratch.chain_merged_dense.clear();
6930            scratch.output_buf = output_scratch;
6931            scratch.single_path_aux_dense = single_path_aux;
6932            scratch.single_path_acc_dense = single_path_acc;
6933        };
6934
6935        if use_stack_plans {
6936            for (path_index, (original_tokenizer_state, terminals_disallowed, _)) in
6937                paths.iter().enumerate()
6938            {
6939                let internal_tsid = self
6940                    .constraint
6941                    .internal_tsid_for_state(*original_tokenizer_state);
6942                let seed_base = &self.constraint.seed_universe_dense;
6943                let mut dense_is_seed = terminals_disallowed.is_empty();
6944                if dense_is_seed {
6945                    if seed_base.is_empty() {
6946                        continue;
6947                    }
6948                } else if !self.fill_single_path_seed_dense(
6949                    terminals_disallowed,
6950                    &mut single_path_aux,
6951                    &mut single_path_acc,
6952                ) {
6953                    continue;
6954                }
6955
6956                let plan = &stack_plans[path_plan_indices[path_index] as usize];
6957                for op in &plan_ops[plan.ops_start..plan.ops_end] {
6958                    match *op {
6959                        SinglePathDirectPlanOp::Merge(weight) => {
6960                            used_direct_final = true;
6961                            let dense = if dense_is_seed {
6962                                seed_base.as_ref()
6963                            } else {
6964                                single_path_acc.as_slice()
6965                            };
6966                            self.merge_single_path_final_weight_to_internal(
6967                                weight,
6968                                internal_tsid,
6969                                dense,
6970                                precomputed,
6971                                &mut merged,
6972                                Some(&mut *buf),
6973                                &mut direct_buf_dirty,
6974                            );
6975                            if weight.is_full() {
6976                                break;
6977                            }
6978                        }
6979                        SinglePathDirectPlanOp::Intersect(weight) => {
6980                            if dense_is_seed {
6981                                if weight.is_full() {
6982                                    continue;
6983                                }
6984                                if !materialize_single_path_seed_intersection(
6985                                    seed_base,
6986                                    &mut single_path_acc,
6987                                    internal_tsid,
6988                                    weight,
6989                                    &self.constraint,
6990                                ) {
6991                                    break;
6992                                }
6993                                dense_is_seed = false;
6994                            } else if !Self::intersect_single_path_dense_with_weight_in_place(
6995                                &mut single_path_acc,
6996                                &mut single_path_aux,
6997                                internal_tsid,
6998                                weight,
6999                                &self.constraint,
7000                            ) {
7001                                break;
7002                            }
7003                        }
7004                    }
7005                }
7006            }
7007        } else {
7008            for (original_tokenizer_state, terminals_disallowed, stack) in &paths {
7009                let internal_tsid = self
7010                    .constraint
7011                    .internal_tsid_for_state(*original_tokenizer_state);
7012                let seed_base = &self.constraint.seed_universe_dense;
7013                let mut dense_is_seed = terminals_disallowed.is_empty();
7014                if dense_is_seed {
7015                    if seed_base.is_empty() {
7016                        continue;
7017                    }
7018                } else if !self.fill_single_path_seed_dense(
7019                    terminals_disallowed,
7020                    &mut single_path_aux,
7021                    &mut single_path_acc,
7022                ) {
7023                    continue;
7024                }
7025
7026                walk_single_stack::<true, _>(
7027                    self.constraint.runtime_parser_dwa_start_state(),
7028                    stack,
7029                    |state| self.constraint.runtime_parser_dwa_final_weight(state),
7030                    |state, parser| self.constraint.runtime_parser_dwa_transition(state, parser),
7031                    |event| {
7032                        match event {
7033                            StackWalkEvent::Final(final_weight) => {
7034                                used_direct_final = true;
7035                                let dense = if dense_is_seed {
7036                                    seed_base.as_ref()
7037                                } else {
7038                                    single_path_acc.as_slice()
7039                                };
7040                                self.merge_single_path_final_weight_to_internal(
7041                                    final_weight,
7042                                    internal_tsid,
7043                                    dense,
7044                                    precomputed,
7045                                    &mut merged,
7046                                    Some(&mut *buf),
7047                                    &mut direct_buf_dirty,
7048                                );
7049                                // This stops only the current correlated
7050                                // parser/lexer path. Later paths may still
7051                                // contribute tokens, but this path cannot:
7052                                // its future masks are subsets of `dense`.
7053                                if final_weight.is_full() {
7054                                    return false;
7055                                }
7056                            }
7057                            StackWalkEvent::Top(parser_state) => {
7058                                let positive_label = encode_positive_label(parser_state);
7059                                let dense = if dense_is_seed {
7060                                    seed_base.as_ref()
7061                                } else {
7062                                    single_path_acc.as_slice()
7063                                };
7064                                let mut used_equivalent_wide_summary = false;
7065                                if let Some(summary) = self
7066                                    .constraint
7067                                    .direct_regular_wide_acceptance_for_parser_state(parser_state)
7068                                    && let Some(accepted) = summary.dense_by_tsid.get(internal_tsid)
7069                                {
7070                                    let n = dense.len().min(accepted.len()).min(merged.len());
7071                                    for word in 0..n {
7072                                        merged[word] |= dense[word] & accepted[word];
7073                                    }
7074                                    used_direct_final = true;
7075                                    used_equivalent_wide_summary = true;
7076                                }
7077
7078                                if !used_equivalent_wide_summary {
7079                                    if let Some(accept_weight) =
7080                                        self.constraint.runtime_parser_top_accept(positive_label)
7081                                    {
7082                                        used_direct_final = true;
7083                                        self.merge_single_path_final_weight_to_internal(
7084                                            accept_weight,
7085                                            internal_tsid,
7086                                            dense,
7087                                            precomputed,
7088                                            &mut merged,
7089                                            Some(&mut *buf),
7090                                            &mut direct_buf_dirty,
7091                                        );
7092                                    }
7093                                    let accept_parts =
7094                                        self.constraint.runtime_parser_top_accept_parts(positive_label);
7095                                    if !accept_parts.is_empty() {
7096                                        used_direct_final = true;
7097                                        for accept_weight in accept_parts {
7098                                            self.merge_single_path_final_weight_to_internal(
7099                                                accept_weight,
7100                                                internal_tsid,
7101                                                dense,
7102                                                precomputed,
7103                                                &mut merged,
7104                                                Some(&mut *buf),
7105                                                &mut direct_buf_dirty,
7106                                            );
7107                                        }
7108                                    }
7109                                    let used_l1 = self.constraint.for_each_direct_regular_l1_acceptance(
7110                                        parser_state,
7111                                        |accept_weight| {
7112                                            self.merge_single_path_final_weight_to_internal(
7113                                                accept_weight,
7114                                                internal_tsid,
7115                                                dense,
7116                                                precomputed,
7117                                                &mut merged,
7118                                                Some(&mut *buf),
7119                                                &mut direct_buf_dirty,
7120                                            );
7121                                        },
7122                                    );
7123                                    used_direct_final |= used_l1;
7124                                }
7125                            }
7126                            StackWalkEvent::Intersect(weight) => {
7127                                if dense_is_seed {
7128                                    if !weight.is_full() {
7129                                        if !materialize_single_path_seed_intersection(
7130                                            seed_base,
7131                                            &mut single_path_acc,
7132                                            internal_tsid,
7133                                            weight,
7134                                            &self.constraint,
7135                                        ) {
7136                                            return false;
7137                                        }
7138                                        dense_is_seed = false;
7139                                    }
7140                                } else if !Self::intersect_single_path_dense_with_weight_in_place(
7141                                    &mut single_path_acc,
7142                                    &mut single_path_aux,
7143                                    internal_tsid,
7144                                    weight,
7145                                    &self.constraint,
7146                                ) {
7147                                    return false;
7148                                }
7149                            }
7150                        }
7151                        true
7152                    },
7153                );
7154            }
7155        }
7156        if !used_direct_final && !self.frontier_complete() {
7157            restore_scratch(merged, output_scratch, single_path_aux, single_path_acc);
7158            return false;
7159        }
7160
7161        if merged.iter().any(|&word| word != 0) {
7162            let buf_zeroed = !direct_buf_dirty;
7163            self.constraint.or_internal_dense_to_buf_fast_with_scratch(
7164                &merged,
7165                buf,
7166                buf_zeroed,
7167                &mut output_scratch,
7168            );
7169        }
7170        if direct_buf_dirty {
7171            self.store_mask_cache_reuse_dense(buf);
7172        } else {
7173            self.store_mask_cache(buf, &merged);
7174        }
7175        restore_scratch(merged, output_scratch, single_path_aux, single_path_acc);
7176        true
7177    }
7178
7179    fn try_fill_mask_from_cache(&self, buf: &mut [u32]) -> bool {
7180        let cache = self.mask_cache.lock().unwrap();
7181
7182        let Some(cache_data) = cache.as_ref() else {
7183            return false;
7184        };
7185
7186        if cache_data.generation != self.generation() {
7187            return false;
7188        }
7189
7190        buf.copy_from_slice(&cache_data.mask);
7191        true
7192    }
7193
7194    fn store_mask_cache(&self, buf: &[u32], merged_dense: &[u64]) {
7195        self.mask_cache.store(self.generation(), buf, merged_dense);
7196    }
7197
7198    fn fill_single_path_seed_dense(
7199        &self,
7200        terminals_disallowed: &TerminalsDisallowed,
7201        aux: &mut Vec<u64>,
7202        dense: &mut Vec<u64>,
7203    ) -> bool {
7204        let base = &self.constraint.seed_universe_dense;
7205        if base.is_empty() {
7206            dense.clear();
7207            return false;
7208        }
7209
7210        dense.clear();
7211        dense.extend_from_slice(base);
7212
7213        if terminals_disallowed.is_empty() {
7214            return true;
7215        }
7216
7217        self.fill_blocked_seed_dense(terminals_disallowed, aux);
7218
7219        if aux.iter().all(|&word| word == 0) {
7220            return true;
7221        }
7222
7223        let mut any = false;
7224        for (allowed_word, blocked_word) in dense.iter_mut().zip(aux.iter().copied()) {
7225            *allowed_word &= !blocked_word;
7226            any |= *allowed_word != 0;
7227        }
7228        any
7229    }
7230
7231    fn intersect_single_path_dense_with_weight_in_place(
7232        dense: &mut Vec<u64>,
7233        aux: &mut Vec<u64>,
7234        internal_tsid: u32,
7235        weight: RuntimeWeightRef<'_>,
7236        constraint: &Constraint,
7237    ) -> bool {
7238        intersect_static_dense_with_weight(dense, aux, internal_tsid, weight,
7239            |tokens| constraint.runtime_token_set_dense_mask(tokens))
7240    }
7241
7242    fn merge_single_path_final_weight_to_internal(
7243        &self,
7244        final_weight: RuntimeWeightRef<'_>,
7245        internal_tsid: u32,
7246        dense: &[u64],
7247        precomputed: &DenseTokenMaskCache,
7248        merged: &mut [u64],
7249        mut direct_buf: Option<&mut [u32]>,
7250        direct_buf_dirty: &mut bool,
7251    ) -> bool {
7252        if final_weight.is_full() {
7253            let n = dense.len().min(merged.len());
7254            for idx in 0..n {
7255                merged[idx] |= dense[idx];
7256            }
7257            return false;
7258        }
7259
7260        let Some(token_set) = final_weight.token_set_for_tsid(internal_tsid) else {
7261            return true;
7262        };
7263        if let (Some(buf), RuntimeTokenSetRef::Materialized(token_set)) =
7264            (direct_buf.as_deref_mut(), token_set)
7265        {
7266            let token_set_key = Arc::as_ptr(token_set) as usize;
7267            if self
7268                .constraint
7269                .direct_sparse_weight_token_sets
7270                .contains(&token_set_key)
7271                && self
7272                    .constraint
7273                    .or_dense_token_set_to_buf_sparse(dense, token_set, 2048, buf)
7274                    .is_some()
7275            {
7276                *direct_buf_dirty = true;
7277                return true;
7278            }
7279            if self
7280                .constraint
7281                .or_weight_token_set_to_buf_if_contained(dense, token_set, buf)
7282            {
7283                *direct_buf_dirty = true;
7284                return true;
7285            }
7286        }
7287
7288        if let (Some(buf), RuntimeTokenSetRef::PackedPool(tokens)) =
7289            (direct_buf, token_set)
7290            && self.constraint.or_packed_final_tokens_to_buf(dense, tokens, buf)
7291        {
7292            *direct_buf_dirty = true;
7293            return true;
7294        }
7295
7296        DenseMaskAcc::or_dense_and_runtime_token_set_into(dense, token_set, precomputed, merged);
7297        false
7298    }
7299
7300    fn terminals_disallowed_to_dense_acc(
7301        &self,
7302        terminals_disallowed: &TerminalsDisallowed,
7303        tokenizer_state: u32,
7304    ) -> Option<DenseMaskAcc> {
7305        let internal_tsids = self
7306            .constraint
7307            .runtime_internal_tsids_for_tokenizer_state(tokenizer_state)?;
7308        let base = &self.constraint.seed_universe_dense;
7309        if base.is_empty() || internal_tsids.is_empty() {
7310            return None;
7311        }
7312        if terminals_disallowed.is_empty() {
7313            return DenseMaskAcc::from_dense_arc_for_tsids(
7314                &internal_tsids,
7315                Arc::clone(base),
7316            );
7317        }
7318
7319        let mut blocked_only = Vec::new();
7320        self.fill_blocked_seed_dense(terminals_disallowed, &mut blocked_only);
7321
7322        if blocked_only.iter().all(|&word| word == 0) {
7323            return DenseMaskAcc::from_dense_arc_for_tsids(
7324                &internal_tsids,
7325                Arc::clone(base),
7326            );
7327        }
7328
7329        let mut dense = base.to_vec();
7330        for (allowed_word, blocked_word) in dense.iter_mut().zip(blocked_only) {
7331            *allowed_word &= !blocked_word;
7332        }
7333
7334        DenseMaskAcc::from_dense_arc_for_tsids(&internal_tsids, dense.into())
7335    }
7336
7337    fn merge_final_weight_to_internal(
7338        &self,
7339        final_weight: RuntimeWeightRef<'_>,
7340        acc: &DenseMaskAcc,
7341        precomputed: &DenseTokenMaskCache,
7342        merged: &mut [u64],
7343        mut direct_buf: Option<&mut [u32]>,
7344        direct_buf_dirty: &mut bool,
7345    ) -> bool {
7346        let mut all_direct = true;
7347        if final_weight.is_full() {
7348            for (_, dense) in &acc.0 {
7349                let n = dense.len().min(merged.len());
7350                for i in 0..n {
7351                    merged[i] |= dense[i];
7352                }
7353                all_direct = false;
7354            }
7355        } else {
7356            for (tsid, dense) in &acc.0 {
7357                let Some(token_set) = final_weight.token_set_for_tsid(*tsid) else {
7358                    continue;
7359                };
7360
7361                let handled_directly = if let (Some(buf), RuntimeTokenSetRef::Materialized(token_set)) =
7362                    (direct_buf.as_deref_mut(), token_set)
7363                {
7364                    let token_set_key = Arc::as_ptr(token_set) as usize;
7365                    if (self
7366                        .constraint
7367                        .direct_sparse_weight_token_sets
7368                        .contains(&token_set_key)
7369                        && self
7370                            .constraint
7371                            .or_dense_token_set_to_buf_sparse(dense, token_set, 2048, buf)
7372                            .is_some())
7373                        || self
7374                            .constraint
7375                            .or_weight_token_set_to_buf_if_contained(dense, token_set, buf)
7376                    {
7377                        *direct_buf_dirty = true;
7378                        true
7379                    } else {
7380                        false
7381                    }
7382                } else {
7383                    false
7384                };
7385
7386                if !handled_directly {
7387                    DenseMaskAcc::or_dense_and_runtime_token_set_into(dense, token_set, precomputed, merged);
7388                    all_direct = false;
7389                }
7390            }
7391        }
7392
7393        all_direct
7394    }
7395
7396    fn merge_final_weight_for_accs(
7397        &self,
7398        final_weight: RuntimeWeightRef<'_>,
7399        accs: &[DenseMaskAcc],
7400        precomputed: &DenseTokenMaskCache,
7401        merged: &mut [u64],
7402        direct_buf: &mut Option<&mut [u32]>,
7403        direct_buf_dirty: &mut bool,
7404    ) -> bool {
7405        let mut all_direct = true;
7406        for acc in accs {
7407            all_direct &= self.merge_final_weight_to_internal(
7408                final_weight,
7409                acc,
7410                precomputed,
7411                merged,
7412                direct_buf.as_deref_mut(),
7413                direct_buf_dirty,
7414            );
7415        }
7416        all_direct
7417    }
7418
7419    fn merge_final_weight_for_gss(
7420        &self,
7421        final_weight: RuntimeWeightRef<'_>,
7422        gss: &DenseMaskGSS,
7423        precomputed: &DenseTokenMaskCache,
7424        merged: &mut [u64],
7425        direct_buf: &mut Option<&mut [u32]>,
7426        direct_buf_dirty: &mut bool,
7427    ) -> bool {
7428        let mut all_direct = true;
7429        gss.for_each_acc(|acc| {
7430            all_direct &= self.merge_final_weight_to_internal(
7431                final_weight,
7432                acc,
7433                precomputed,
7434                merged,
7435                direct_buf.as_deref_mut(),
7436                direct_buf_dirty,
7437            );
7438        });
7439        all_direct
7440    }
7441
7442    fn try_seed_direct_regular_wide_frontier(
7443        &self,
7444        gss: &ParserGSS,
7445        original_tokenizer_state: u32,
7446        start_final_weight: Option<RuntimeWeightRef<'_>>,
7447        start_dwa_state: u32,
7448        precomputed: &DenseTokenMaskCache,
7449        merged: &mut [u64],
7450        direct_buf: &mut Option<&mut [u32]>,
7451        direct_buf_possible: &mut bool,
7452        direct_buf_used: &mut bool,
7453        direct_buf_dirty: &mut bool,
7454    ) -> bool {
7455        if !self
7456            .constraint
7457            .runtime_parser_dwa_row_is_empty(start_dwa_state)
7458        {
7459            return false;
7460        }
7461        let Some(summary) = self.constraint.direct_regular_wide_frontier_for_gss(gss) else {
7462            return false;
7463        };
7464        let Some(terminals_disallowed) = gss.uniform_accumulator() else {
7465            return false;
7466        };
7467
7468        let Some(dense_acc) = self.terminals_disallowed_to_dense_acc(
7469            &terminals_disallowed,
7470            original_tokenizer_state,
7471        ) else {
7472            return true;
7473        };
7474
7475        *direct_buf_used = true;
7476        if let Some(weight) = start_final_weight {
7477            *direct_buf_possible &= self.merge_final_weight_to_internal(
7478                weight,
7479                &dense_acc,
7480                precomputed,
7481                merged,
7482                direct_buf.as_deref_mut(),
7483                direct_buf_dirty,
7484            );
7485        }
7486        for (tsid, dense) in &dense_acc.0 {
7487            let Some(accepted) = summary.dense_by_tsid.get(*tsid) else {
7488                continue;
7489            };
7490            let n = dense.len().min(accepted.len()).min(merged.len());
7491            for index in 0..n {
7492                merged[index] |= dense[index] & accepted[index];
7493            }
7494        }
7495        *direct_buf_possible = false;
7496        true
7497    }
7498
7499    fn seed_mask_queue_merged(
7500        &self,
7501        start_final_weight: Option<RuntimeWeightRef<'_>>,
7502        start_dwa_state: u32,
7503        precomputed: &DenseTokenMaskCache,
7504        transition_gss_cache: &mut FxHashMap<DenseGssTransitionKey, DenseMaskGSS>,
7505        transition_intersection_cache: &mut DenseTokenSetIntersectionSmallCache,
7506        queue: &mut MaskQueue,
7507        merged: &mut [u64],
7508        direct_buf: &mut Option<&mut [u32]>,
7509        direct_buf_possible: &mut bool,
7510        direct_buf_used: &mut bool,
7511        direct_buf_dirty: &mut bool,
7512        profile: &mut Option<MaskInnerProfileStats>,
7513    ) {
7514        for (&tokenizer_state, gss) in &self.state {
7515            if gss.is_empty() {
7516                continue;
7517            }
7518
7519            let original_tokenizer_state = tokenizer_state;
7520            if self.try_seed_direct_regular_wide_frontier(
7521                gss,
7522                original_tokenizer_state,
7523                start_final_weight,
7524                start_dwa_state,
7525                precomputed,
7526                merged,
7527                direct_buf,
7528                direct_buf_possible,
7529                direct_buf_used,
7530                direct_buf_dirty,
7531            ) {
7532                continue;
7533            }
7534
7535            let seed_decompose_start = if profile.is_some() {
7536                Some(Instant::now())
7537            } else {
7538                None
7539            };
7540            // Exclusion pruning depends on which parser top makes an overlapping
7541            // terminal actionable. Transforming accumulators before decomposing
7542            // the parser frontier loses that correlation: the union of all top
7543            // states can let a terminal from one parser path rescue a blocked
7544            // token on another. Decompose by top first, then transform every
7545            // accumulator in that top-local sub-GSS with exactly that top state.
7546            let mut decomposed = Vec::new();
7547            gss.for_each_decomposed(|parser_state, popped| {
7548                let dense = popped.apply_and_prune(|terminals_disallowed| {
7549                    self.terminals_disallowed_to_dense_acc(
7550                        terminals_disallowed,
7551                        original_tokenizer_state,
7552                    )
7553                });
7554                if !dense.is_empty() {
7555                    decomposed.push((parser_state, dense));
7556                }
7557            });
7558
7559            // Empty parser-stack paths have no actionable parser top. Preserve
7560            // their root accumulators separately for the parser-DWA start final
7561            // weight, matching apply_transform_and_decompose's old root handling.
7562            let mut root_accs = Vec::new();
7563            gss.isolate(None).for_each_acc(|terminals_disallowed| {
7564                if let Some(acc) = self.terminals_disallowed_to_dense_acc(
7565                    terminals_disallowed,
7566                    original_tokenizer_state,
7567                ) {
7568                    root_accs.push(acc);
7569                }
7570            });
7571            if let (Some(profile), Some(start)) = (profile.as_mut(), seed_decompose_start) {
7572                profile.seed_decompose_ns += elapsed_ns(start);
7573            }
7574
7575            if decomposed.is_empty() && root_accs.is_empty() {
7576                continue;
7577            }
7578
7579            if let Some(final_weight) = start_final_weight {
7580                let accumulate_start = if profile.is_some() {
7581                    Some(Instant::now())
7582                } else {
7583                    None
7584                };
7585                *direct_buf_used = true;
7586                *direct_buf_possible &= self.merge_final_weight_for_accs(
7587                    final_weight,
7588                    &root_accs,
7589                    precomputed,
7590                    merged,
7591                    direct_buf,
7592                    direct_buf_dirty,
7593                );
7594
7595                for (_, sub_gss) in &decomposed {
7596                    *direct_buf_possible &= self.merge_final_weight_for_gss(
7597                        final_weight,
7598                        sub_gss,
7599                        precomputed,
7600                        merged,
7601                        direct_buf,
7602                        direct_buf_dirty,
7603                    );
7604                }
7605                if let (Some(profile), Some(start)) = (profile.as_mut(), accumulate_start) {
7606                    profile.token_accumulation_ns += elapsed_ns(start);
7607                }
7608            }
7609
7610            for (parser_state, popped) in &decomposed {
7611                let positive_label = encode_positive_label(*parser_state);
7612                if let Some(accept_weight) =
7613                    self.constraint.runtime_parser_top_accept(positive_label)
7614                {
7615                    let accumulate_start = if profile.is_some() {
7616                        Some(Instant::now())
7617                    } else {
7618                        None
7619                    };
7620                    *direct_buf_used = true;
7621                    *direct_buf_possible &= self.merge_final_weight_for_gss(
7622                        accept_weight,
7623                        popped,
7624                        precomputed,
7625                        merged,
7626                        direct_buf,
7627                        direct_buf_dirty,
7628                    );
7629                    if let (Some(profile), Some(start)) = (profile.as_mut(), accumulate_start) {
7630                        profile.token_accumulation_ns += elapsed_ns(start);
7631                    }
7632                }
7633                let accept_parts =
7634                    self.constraint.runtime_parser_top_accept_parts(positive_label);
7635                if !accept_parts.is_empty() {
7636                    let accumulate_start = if profile.is_some() {
7637                        Some(Instant::now())
7638                    } else {
7639                        None
7640                    };
7641                    *direct_buf_used = true;
7642                    for accept_weight in accept_parts {
7643                        *direct_buf_possible &= self.merge_final_weight_for_gss(
7644                            accept_weight,
7645                            popped,
7646                            precomputed,
7647                            merged,
7648                            direct_buf,
7649                            direct_buf_dirty,
7650                        );
7651                    }
7652                    if let (Some(profile), Some(start)) = (profile.as_mut(), accumulate_start) {
7653                        profile.token_accumulation_ns += elapsed_ns(start);
7654                    }
7655                }
7656                let accumulate_start = profile.as_ref().map(|_| Instant::now());
7657                let mut l1_direct_possible = true;
7658                let used_l1 = self.constraint.for_each_direct_regular_l1_acceptance(
7659                    *parser_state,
7660                    |accept_weight| {
7661                        l1_direct_possible &= self.merge_final_weight_for_gss(
7662                            accept_weight,
7663                            popped,
7664                            precomputed,
7665                            merged,
7666                            direct_buf,
7667                            direct_buf_dirty,
7668                        );
7669                    },
7670                );
7671                if used_l1 {
7672                    *direct_buf_used = true;
7673                    *direct_buf_possible &= l1_direct_possible;
7674                    if let (Some(profile), Some(start)) = (profile.as_mut(), accumulate_start) {
7675                        profile.token_accumulation_ns += elapsed_ns(start);
7676                    }
7677                }
7678                queue.record_seed_decompose_callback();
7679                enqueue_parser_state_transition(
7680                    &self.constraint,
7681                    queue,
7682                    start_dwa_state,
7683                    *parser_state,
7684                    popped,
7685                    precomputed,
7686                    transition_gss_cache,
7687                    transition_intersection_cache,
7688                    profile,
7689                );
7690            }
7691        }
7692    }
7693
7694    fn fill_mask_indexed_dag(&self, buf: &mut [u32], force: bool) -> bool {
7695        if (!force && !indexed_dag_mask_enabled()) || !self.has_parser_ambiguity() {
7696            return false;
7697        }
7698        let parser_dwa = self.constraint.parser_dwa();
7699        if self.state.is_empty() || parser_dwa.states().is_empty() {
7700            return false;
7701        }
7702        if self.constraint.indexed_dag_dense_transitions.len() != parser_dwa.states().len()
7703            || self.constraint.indexed_dag_dense_finals.len() != parser_dwa.states().len()
7704        {
7705            return false;
7706        }
7707
7708        let profile = indexed_dag_mask_profile_enabled();
7709        let total_started = profile.then(Instant::now);
7710        let precomputed = &self.constraint.weight_token_dense_masks;
7711        let dense_words = self.constraint.internal_token_dense_words;
7712        let mut scratch = mask_scratch(&self.constraint);
7713        let (mut merged, mut indexed_runtime) = {
7714            (
7715                std::mem::take(&mut scratch.merged_dense),
7716                std::mem::take(&mut scratch.indexed_dag_mask),
7717            )
7718        };
7719        indexed_runtime.begin_mask();
7720        merged.clear();
7721        merged.resize(dense_words, 0);
7722        buf.fill(0);
7723        let mut accepted: Option<DenseMaskAcc> = None;
7724        let mut index_ns = 0u64;
7725        let mut eval_ns = 0u64;
7726
7727        let merge_accepted = |accepted: &mut Option<DenseMaskAcc>, incoming: Option<DenseMaskAcc>| {
7728            let Some(incoming) = incoming else {
7729                return;
7730            };
7731            *accepted = Some(match accepted.take() {
7732                Some(existing) => existing.merge(&incoming),
7733                None => incoming,
7734            });
7735        };
7736
7737        let start_state = parser_dwa.start_state();
7738        let start_final_weight = parser_dwa.states()[start_state as usize].final_weight.as_ref();
7739        let start_transitions = &self.constraint.dwa_fast_transitions[start_state as usize];
7740        let mut seed_intersections = DenseTokenSetIntersectionSmallCache::new();
7741        let lower_entries_before = indexed_runtime.lower_memo.len();
7742        let segment_entries_before = indexed_runtime.segment_memo.len();
7743        let accumulator_entries_before = indexed_runtime.accumulators.len();
7744        let mut seed_gsses = Vec::<DenseMaskGSS>::new();
7745        let mut seed_targets = Vec::<u32>::new();
7746        let mut seed_weights = Vec::<Weight>::new();
7747
7748        for (&tokenizer_state, gss) in &self.state {
7749            if gss.is_empty() {
7750                continue;
7751            }
7752            let root_dense = gss.isolate(None).apply_and_prune(|terminals_disallowed| {
7753                self.terminals_disallowed_to_dense_acc(terminals_disallowed, tokenizer_state)
7754            });
7755            if let Some(final_weight) = start_final_weight {
7756                root_dense.for_each_acc(|accumulator| {
7757                    merge_accepted(
7758                        &mut accepted,
7759                        accumulator.intersect_with_weight_small_cached(
7760                            final_weight,
7761                            precomputed,
7762                            &mut seed_intersections,
7763                        ),
7764                    );
7765                });
7766            }
7767
7768            gss.for_each_decomposed(|parser_state, popped| {
7769                let dense = popped.apply_and_prune(|terminals_disallowed| {
7770                    self.terminals_disallowed_to_dense_acc(
7771                        terminals_disallowed,
7772                        tokenizer_state,
7773                    )
7774                });
7775                if dense.is_empty() {
7776                    return;
7777                }
7778                if let Some(final_weight) = start_final_weight {
7779                    dense.for_each_acc(|accumulator| {
7780                        merge_accepted(
7781                            &mut accepted,
7782                            accumulator.intersect_with_weight_small_cached(
7783                                final_weight,
7784                                precomputed,
7785                                &mut seed_intersections,
7786                            ),
7787                        );
7788                    });
7789                }
7790                let positive_label = encode_positive_label(parser_state);
7791                if let Some(top_weight) = self
7792                    .constraint
7793                    .parser_top_accept
7794                    .get(&positive_label)
7795                    .or_else(|| self.constraint.parser_top_accept.get(&DEFAULT_LABEL))
7796                {
7797                    dense.for_each_acc(|accumulator| {
7798                        merge_accepted(
7799                            &mut accepted,
7800                            accumulator.intersect_with_weight_small_cached(
7801                                top_weight,
7802                                precomputed,
7803                                &mut seed_intersections,
7804                            ),
7805                        );
7806                    });
7807                }
7808                if let Some(top_parts) = self
7809                    .constraint
7810                    .parser_top_accept_parts
7811                    .get(&positive_label)
7812                    .or_else(|| {
7813                        self.constraint
7814                            .parser_top_accept_parts
7815                            .get(&DEFAULT_LABEL)
7816                    })
7817                {
7818                    for top_weight in top_parts {
7819                        dense.for_each_acc(|accumulator| {
7820                            merge_accepted(
7821                                &mut accepted,
7822                            accumulator.intersect_with_weight_small_cached(
7823                                    top_weight,
7824                                    precomputed,
7825                                    &mut seed_intersections,
7826                                ),
7827                            );
7828                        });
7829                    }
7830                }
7831                self.constraint.for_each_direct_regular_l1_acceptance(
7832                    parser_state,
7833                    |top_weight| {
7834                        let RuntimeWeightRef::Materialized(top_weight) = top_weight else {
7835                            return;
7836                        };
7837                        dense.for_each_acc(|accumulator| {
7838                            merge_accepted(
7839                                &mut accepted,
7840                                accumulator.intersect_with_weight_small_cached(
7841                                    top_weight,
7842                                    precomputed,
7843                                    &mut seed_intersections,
7844                                ),
7845                            );
7846                        });
7847                    },
7848                );
7849                let Some((target, transition_weight)) = self
7850                    .constraint
7851                    .fast_parser_dwa_transition(start_transitions, parser_state)
7852                else {
7853                    return;
7854                };
7855                seed_gsses.push(dense);
7856                seed_targets.push(target);
7857                seed_weights.push(transition_weight.clone());
7858            });
7859        }
7860
7861        let mut indexed_nodes = 0usize;
7862        let mut upper_entries = 0usize;
7863        let mut lower_entries = 0usize;
7864        let mut segment_entries = 0usize;
7865        let mut upper_calls = 0u64;
7866        let mut upper_hits = 0u64;
7867        let mut lower_calls = 0u64;
7868        let mut lower_hits = 0u64;
7869        let mut segment_calls = 0u64;
7870        let mut segment_hits = 0u64;
7871        let mut memo_result_entries = 0u64;
7872        let mut memo_dense_words = 0u64;
7873        let mut memo_nonzero_words = 0u64;
7874        let mut memo_max_nonzero_words = 0u64;
7875
7876        if !seed_gsses.is_empty() {
7877            let started = profile.then(Instant::now);
7878            let index_nodes = std::mem::take(&mut indexed_runtime.index_nodes);
7879            let index_roots = std::mem::take(&mut indexed_runtime.index_roots);
7880            let index_lower_ids = std::mem::take(&mut indexed_runtime.index_lower_ids);
7881            let index_upper_ids = std::mem::take(&mut indexed_runtime.index_upper_ids);
7882            let (dag, roots, index_lower_ids, index_upper_ids) =
7883                DenseMaskGSS::indexed_dag_many_reusing(
7884                    &seed_gsses,
7885                    index_nodes,
7886                    index_roots,
7887                    index_lower_ids,
7888                    index_upper_ids,
7889                );
7890            if let Some(started) = started {
7891                index_ns += elapsed_ns(started);
7892            }
7893            indexed_nodes = dag.nodes.len();
7894            let started = profile.then(Instant::now);
7895            let mut evaluator = IndexedDagMaskEvaluator::new(
7896                &self.constraint,
7897                &dag,
7898                precomputed,
7899                &mut indexed_runtime,
7900            );
7901            for (((root, target), transition_weight), _) in roots
7902                .iter()
7903                .copied()
7904                .zip(seed_targets)
7905                .zip(seed_weights)
7906                .zip(seed_gsses)
7907            {
7908                let result = evaluator.eval_upper(target, root);
7909                let result = result.and_then(|result| {
7910                    result.intersect_with_weight_small_cached(
7911                        &transition_weight,
7912                        precomputed,
7913                        &mut seed_intersections,
7914                    )
7915                });
7916                merge_accepted(&mut accepted, result);
7917            }
7918            if let Some(started) = started {
7919                eval_ns += elapsed_ns(started);
7920            }
7921            upper_entries = evaluator.upper_memo.len();
7922            lower_entries = evaluator.runtime.lower_memo.len();
7923            segment_entries = evaluator.runtime.segment_memo.len();
7924            upper_calls = evaluator.upper_calls;
7925            upper_hits = evaluator.upper_hits;
7926            lower_calls = evaluator.lower_calls;
7927            lower_hits = evaluator.lower_hits;
7928            segment_calls = evaluator.segment_calls;
7929            segment_hits = evaluator.segment_hits;
7930            memo_result_entries = evaluator.memo_result_entries;
7931            memo_dense_words = evaluator.memo_dense_words;
7932            memo_nonzero_words = evaluator.memo_nonzero_words;
7933            memo_max_nonzero_words = evaluator.memo_max_nonzero_words;
7934            indexed_runtime.retain_index_scratch(
7935                dag,
7936                roots,
7937                index_lower_ids,
7938                index_upper_ids,
7939            );
7940        }
7941
7942        if let Some(accepted) = accepted {
7943            accepted.or_into_merged(&mut merged);
7944        }
7945        self.constraint.or_internal_dense_to_buf_fast(&merged, buf, true);
7946        self.store_mask_cache(buf, &merged);
7947        let accumulator_entries_total = indexed_runtime.accumulators.len();
7948        indexed_runtime.prune_stale_sources_if_needed();
7949        {
7950            scratch.merged_dense = merged;
7951            scratch.indexed_dag_mask = indexed_runtime;
7952        }
7953        if let Some(started) = total_started {
7954            eprintln!(
7955                "[glrmask/profile][indexed_dag_mask] total_ns={} index_ns={} eval_ns={} indexed_nodes={} upper_entries={} lower_entries_added={} lower_entries_total={} segment_entries_added={} segment_entries_total={} accumulator_entries_added={} accumulator_entries_total={} upper_calls={} upper_hits={} lower_calls={} lower_hits={} segment_calls={} segment_hits={} memo_result_entries={} memo_dense_words={} memo_nonzero_words={} memo_max_nonzero_words={}",
7956                elapsed_ns(started),
7957                index_ns,
7958                eval_ns,
7959                indexed_nodes,
7960                upper_entries,
7961                lower_entries.saturating_sub(lower_entries_before),
7962                lower_entries,
7963                segment_entries.saturating_sub(segment_entries_before),
7964                segment_entries,
7965                accumulator_entries_total.saturating_sub(accumulator_entries_before),
7966                accumulator_entries_total,
7967                upper_calls,
7968                upper_hits,
7969                lower_calls,
7970                lower_hits,
7971                segment_calls,
7972                segment_hits,
7973                memo_result_entries,
7974                memo_dense_words,
7975                memo_nonzero_words,
7976                memo_max_nonzero_words,
7977            );
7978        }
7979        true
7980    }
7981
7982    fn try_fill_mask_indexed_dag(&self, buf: &mut [u32]) -> bool {
7983        self.fill_mask_indexed_dag(buf, false)
7984    }
7985
7986    fn store_mask_cache_reuse_dense(&self, buf: &[u32]) {
7987        self.mask_cache.store(self.generation(), buf, &[]);
7988    }
7989
7990    fn touch_mask_cache_generation(&self) {
7991        let mut cache = self.mask_cache.lock().unwrap();
7992        if let Some(cache_data) = cache.as_mut() {
7993            cache_data.generation = self.generation();
7994        }
7995    }
7996
7997    fn fill_mask_uncached(&self, buf: &mut [u32]) {
7998        let _ = self.fill_mask_uncached_maybe_profile(buf, false);
7999    }
8000
8001    fn fill_mask_uncached_maybe_profile(
8002        &self,
8003        buf: &mut [u32],
8004        force_profile: bool,
8005    ) -> Option<MaskProfile> {
8006        let total_start = (force_profile || mask_inner_profile_enabled()).then(Instant::now);
8007
8008        if self.try_fill_mask_single_path_direct(buf) {
8009            return total_start.map(|start| MaskProfile {
8010                total_ns: elapsed_ns(start),
8011                single_path_direct: 1,
8012                ..MaskProfile::default()
8013            });
8014        }
8015
8016        if self.try_fill_mask_indexed_dag(buf) {
8017            return total_start.map(|start| MaskProfile {
8018                total_ns: elapsed_ns(start),
8019                ..MaskProfile::default()
8020            });
8021        }
8022
8023        self.fill_mask_uncached_queue(buf, force_profile, total_start)
8024    }
8025
8026    fn fill_mask_uncached_queue(
8027        &self,
8028        buf: &mut [u32],
8029        force_profile: bool,
8030        total_start: Option<Instant>,
8031    ) -> Option<MaskProfile> {
8032        if self.state.is_empty() || self.constraint.runtime_parser_dwa_state_count() == 0 {
8033            buf.fill(0);
8034            self.store_mask_cache(buf, &[]);
8035            return total_start.map(|start| MaskProfile {
8036                total_ns: elapsed_ns(start),
8037                ..MaskProfile::default()
8038            });
8039        }
8040
8041        let precomputed = &self.constraint.weight_token_dense_masks;
8042        let dense_words = self.constraint.internal_token_dense_words;
8043        let mut transition_gss_cache: FxHashMap<DenseGssTransitionKey, DenseMaskGSS> =
8044            FxHashMap::default();
8045        let mut transition_intersection_cache = DenseTokenSetIntersectionSmallCache::new();
8046
8047        let mut scratch = mask_scratch(&self.constraint);
8048        let mut merged = {
8049            std::mem::take(&mut scratch.merged_dense)
8050        };
8051
8052        buf.fill(0);
8053        merged.clear();
8054        merged.resize(dense_words, 0);
8055        let mut direct_buf = None;
8056        let mut direct_buf_possible = true;
8057        let mut direct_buf_used = false;
8058        let mut direct_buf_dirty = false;
8059
8060        let mut queue = MaskQueue::new();
8061        let mut profile = if force_profile || mask_inner_profile_enabled() {
8062            Some(MaskInnerProfileStats::default())
8063        } else {
8064            None
8065        };
8066        let delta_profile_enabled = profile.is_some() && mask_delta_profile_enabled();
8067
8068        let start_state = self.constraint.runtime_parser_dwa_start_state();
8069        let start_final_weight = self.constraint.runtime_parser_dwa_final_weight(start_state);
8070
8071        self.seed_mask_queue_merged(
8072            start_final_weight,
8073            start_state,
8074            precomputed,
8075            &mut transition_gss_cache,
8076            &mut transition_intersection_cache,
8077            &mut queue,
8078            &mut merged,
8079            &mut direct_buf,
8080            &mut direct_buf_possible,
8081            &mut direct_buf_used,
8082            &mut direct_buf_dirty,
8083            &mut profile,
8084        );
8085
8086        walk_static_dwa_gss_queue(
8087            &mut queue,
8088            &mut profile,
8089            |state| self.constraint.runtime_parser_dwa_final_weight(state),
8090            |state, parser| self.constraint.runtime_parser_dwa_transition(state, parser),
8091            |final_weight, gss| {
8092                direct_buf_used = true;
8093                direct_buf_possible &= self.merge_final_weight_for_gss(
8094                    final_weight,
8095                    gss,
8096                    precomputed,
8097                    &mut merged,
8098                    &mut direct_buf,
8099                    &mut direct_buf_dirty,
8100                );
8101            },
8102            |queue, target, weight, popped, profile| {
8103                enqueue_weighted_transition(
8104                    queue,
8105                    popped,
8106                    target,
8107                    weight,
8108                    precomputed,
8109                    &mut transition_gss_cache,
8110                    &mut transition_intersection_cache,
8111                    profile,
8112                );
8113            },
8114        );
8115
8116        if mask_queue_debug_enabled() {
8117            let debug = queue.debug_stats();
8118            let line = format!(
8119                "[glrmask/debug][mask_queue] mode={:?} enqueue_calls={} merge_hits={} fuse_calls={} fuse_changed_depth={} stale_skips={} popped_items={} seed_decompose_callbacks={} loop_decompose_callbacks={} parser_dwa_transitions_enqueued={}",
8120                mask_queue_mode(),
8121                debug.enqueue_calls,
8122                debug.merge_hit_count,
8123                debug.fuse_calls,
8124                debug.fuse_changed_depth,
8125                debug.stale_schedule_skips,
8126                debug.popped_items,
8127                debug.seed_decompose_callbacks,
8128                debug.loop_decompose_callbacks,
8129                debug.parser_dwa_transitions_enqueued,
8130            );
8131            emit_mask_queue_debug_line(&line);
8132        }
8133
8134        let finalize_start = profile.as_ref().map(|_| Instant::now());
8135
8136        let merged_has_leftovers = merged.iter().any(|&word| word != 0);
8137        let direct_finalized = direct_buf_used && direct_buf_possible && !merged_has_leftovers;
8138        let can_use_merged_cache = !direct_buf_dirty;
8139        let mut use_delta_seed = direct_finalized;
8140        let mut reuse_existing_cache_dense = false;
8141        if !direct_finalized && can_use_merged_cache {
8142            let cache = self.mask_cache.lock().unwrap();
8143            if let Some(cache_data) = cache.as_ref()
8144                && cache_data.mask.len() == buf.len()
8145                    && cache_data.merged_dense.len() == merged.len()
8146                    && cache_data.merged_dense == merged
8147                {
8148                    let zero_start = profile.as_ref().map(|_| Instant::now());
8149                    buf.copy_from_slice(&cache_data.mask);
8150                    if let (Some(profile), Some(start)) = (profile.as_mut(), zero_start) {
8151                        profile.finalize_zero_ns += elapsed_ns(start);
8152                        profile.finalize_equal_dense_copy_seed = 1;
8153                        if delta_profile_enabled {
8154                            profile.delta_prev_available = 1;
8155                            profile.delta_unchanged_words = merged.len() as u64;
8156                            profile.delta_copy_cost_words = self.constraint.body_mask_len() as u64;
8157                            profile.delta_used_seed = 1;
8158                        }
8159                    }
8160                    reuse_existing_cache_dense = true;
8161                    use_delta_seed = true;
8162                }
8163            if !use_delta_seed
8164                && let Some(cache_data) = cache.as_ref().filter(|c| c.merged_dense.len() == merged.len()) {
8165                    let scratch_cost = self.constraint.estimate_internal_dense_to_buf_cost(&merged);
8166                    let copy_cost_words = self.constraint.body_mask_len() as u64;
8167                    let mut added_bits = 0u64;
8168                    let mut removed_bits = 0u64;
8169                    let mut unchanged_words = 0u64;
8170                    let mut unchanged_bits = 0u64;
8171                    let mut added_cost = 0u64;
8172                    let mut removed_cost = 0u64;
8173                    let capture_delta_summary = delta_profile_enabled;
8174                    let n_internal = self.constraint.internal_token_count();
8175                    let word_len = merged.len().max(cache_data.merged_dense.len());
8176                    for wi in 0..word_len {
8177                        if wi * 64 >= n_internal {
8178                            break;
8179                        }
8180                        let remaining = n_internal - wi * 64;
8181                        let valid_mask = if remaining >= 64 { !0u64 } else { (1u64 << remaining) - 1 };
8182                        let current = merged.get(wi).copied().unwrap_or(0) & valid_mask;
8183                        let previous = cache_data.merged_dense.get(wi).copied().unwrap_or(0) & valid_mask;
8184                        if capture_delta_summary && current == previous {
8185                            unchanged_words += 1;
8186                        }
8187                        if capture_delta_summary {
8188                            unchanged_bits += (!(current ^ previous) & valid_mask).count_ones() as u64;
8189                        }
8190
8191                        let added = current & !previous;
8192                        if capture_delta_summary {
8193                            added_bits += added.count_ones() as u64;
8194                        }
8195                        if added == valid_mask {
8196                            if let Some(group_mask) = self.constraint.word_group_sparse_masks.get(wi) {
8197                                added_cost += group_mask.len() as u64;
8198                            } else {
8199                                added_cost += self
8200                                    .constraint
8201                                    .internal_bits_grouped_buf_op_cost(wi, added, valid_mask, copy_cost_words as usize)
8202                                    as u64;
8203                            }
8204                        } else if added != 0 {
8205                            added_cost += self
8206                                .constraint
8207                                .internal_bits_grouped_buf_op_cost(wi, added, valid_mask, copy_cost_words as usize)
8208                                as u64;
8209                        }
8210
8211                        let removed = previous & !current;
8212                        if capture_delta_summary {
8213                            removed_bits += removed.count_ones() as u64;
8214                        }
8215                        if removed == valid_mask {
8216                            if let Some(group_mask) = self.constraint.word_group_sparse_masks.get(wi) {
8217                                removed_cost += group_mask.len() as u64;
8218                            } else {
8219                                removed_cost += self
8220                                    .constraint
8221                                    .internal_bits_grouped_buf_op_cost(wi, removed, valid_mask, copy_cost_words as usize)
8222                                    as u64;
8223                            }
8224                        } else if removed != 0 {
8225                            removed_cost += self
8226                                .constraint
8227                                .internal_bits_grouped_buf_op_cost(wi, removed, valid_mask, copy_cost_words as usize)
8228                                as u64;
8229                        }
8230                    }
8231
8232                    let delta_cost = copy_cost_words + added_cost + removed_cost;
8233                    let delta_savings = scratch_cost.saturating_sub(delta_cost);
8234
8235                    if delta_profile_enabled
8236                        && let Some(profile) = profile.as_mut() {
8237                            profile.delta_prev_available = 1;
8238                            profile.delta_added_bits = added_bits;
8239                            profile.delta_removed_bits = removed_bits;
8240                            profile.delta_unchanged_words = unchanged_words;
8241                            profile.delta_unchanged_bits = unchanged_bits;
8242                            profile.delta_added_cost = added_cost;
8243                            profile.delta_removed_cost = removed_cost;
8244                            profile.delta_copy_cost_words = copy_cost_words;
8245                            profile.delta_scratch_estimated_cost = scratch_cost;
8246                            profile.delta_estimated_cost = delta_cost;
8247                            profile.delta_estimated_savings = delta_savings;
8248                        }
8249                    let delta_wins_decisively =
8250                        delta_savings > DELTA_SEED_MIN_SAVINGS && delta_cost.saturating_mul(2) < scratch_cost;
8251                    if delta_wins_decisively && cache_data.mask.len() == buf.len() {
8252                        let zero_start = profile.as_ref().map(|_| Instant::now());
8253                        buf.copy_from_slice(&cache_data.mask);
8254                        if let (Some(profile), Some(start)) = (profile.as_mut(), zero_start) {
8255                            profile.finalize_zero_ns += elapsed_ns(start);
8256                        }
8257
8258                        let dense_to_buf_start = profile.as_ref().map(|_| Instant::now());
8259                        let delta_replay = self.constraint.apply_internal_dense_delta_to_buf(
8260                            &cache_data.merged_dense,
8261                            &merged,
8262                            buf,
8263                        );
8264                        if let Some(profile) = profile.as_mut() {
8265                            profile.delta_replay = delta_replay;
8266                            profile.finalize_delta_replay = 1;
8267                            if delta_profile_enabled {
8268                                profile.delta_used_seed = 1;
8269                            }
8270                            if let Some(start) = dense_to_buf_start {
8271                                profile.finalize_dense_to_buf_ns += elapsed_ns(start);
8272                            }
8273                        }
8274                        use_delta_seed = true;
8275                    }
8276                }
8277        }
8278
8279        if !use_delta_seed {
8280            let dense_to_buf = if direct_finalized || !merged_has_leftovers {
8281                DenseToBufProfileStats::default()
8282            } else {
8283                let buf_zeroed = !direct_buf_dirty;
8284
8285                if profile.is_some() {
8286                    let dense_to_buf_start = Instant::now();
8287                    let dense_to_buf = self
8288                        .constraint
8289                        .or_internal_dense_to_buf(&merged, buf, buf_zeroed);
8290                    if let Some(profile) = profile.as_mut() {
8291                        profile.finalize_dense_to_buf_ns += elapsed_ns(dense_to_buf_start);
8292                    }
8293                    dense_to_buf
8294                } else {
8295                    let fast_conversion_start =
8296                        mask_fast_conversion_profile_enabled().then(Instant::now);
8297                    self.constraint
8298                        .or_internal_dense_to_buf_fast(&merged, buf, buf_zeroed);
8299                    if let Some(start) = fast_conversion_start {
8300                        let merged_set_bits =
8301                            merged.iter().map(|word| word.count_ones() as u64).sum::<u64>();
8302                        emit_mask_fast_conversion_profile_line(&format!(
8303                            "[glrmask/debug][mask_fast_conversion] ns={} internal_set_bits={} buf_words={} direct_buf_used={} direct_buf_possible={}",
8304                            elapsed_ns(start),
8305                            merged_set_bits,
8306                            buf.len(),
8307                            direct_buf_used,
8308                            direct_buf_possible
8309                        ));
8310                    }
8311                    DenseToBufProfileStats::default()
8312                }
8313            };
8314            if let Some(profile) = profile.as_mut() {
8315                profile.finalize_scratch_rebuild = 1;
8316                profile.dense_to_buf = dense_to_buf;
8317            }
8318        }
8319        // NOTE: NEVER EVER add any post-filter here that rechecks candidate
8320        // mask tokens through commit semantics. If mask and commit disagree,
8321        // the bug is in the seed/DWA mask construction logic itself and must
8322        // be fixed there. Hiding the mismatch with a second-pass filter is not
8323        // allowed. This note is intentional and must NEVER EVER be removed.
8324        let cache_start = profile.as_ref().map(|_| Instant::now());
8325        if can_use_merged_cache {
8326            if reuse_existing_cache_dense {
8327                self.touch_mask_cache_generation();
8328            } else {
8329                self.store_mask_cache(buf, &merged);
8330            }
8331        } else {
8332            self.store_mask_cache_reuse_dense(buf);
8333        }
8334        if let (Some(profile), Some(start)) = (profile.as_mut(), cache_start) {
8335            profile.finalize_cache_ns += elapsed_ns(start);
8336        }
8337        let queue_debug = queue.debug_stats();
8338
8339        if let Some(profile) = profile.as_mut() {
8340            if let Some(start) = finalize_start {
8341                profile.finalize_ns += elapsed_ns(start);
8342            }
8343            profile.queue_pop_ns = queue.debug_stats().pop_total_ns;
8344            if let Some(start) = total_start {
8345                profile.total_ns = elapsed_ns(start);
8346            }
8347
8348            let loop_decompose_ns = profile
8349                .loop_decompose_total_ns
8350                .saturating_sub(profile.loop_decompose_callback_ns);
8351            let enqueue_exclusive_ns = queue_debug
8352                .enqueue_total_ns
8353                .saturating_sub(queue_debug.fuse_total_ns);
8354            let accounted_ns = profile.seed_decompose_ns
8355                + profile.queue_pop_ns
8356                + loop_decompose_ns
8357                + profile.transition_lookup_ns
8358                + profile.transition_apply_ns
8359                + profile.token_accumulation_ns
8360                + enqueue_exclusive_ns
8361                + queue_debug.fuse_total_ns
8362                + profile.finalize_ns;
8363            let other_ns = profile.total_ns.saturating_sub(accounted_ns);
8364            let line = format!(
8365                "[glrmask/debug][mask_inner] queue_mode={:?} total_ns={} seed_decompose_ns={} queue_pop_ns={} loop_decompose_ns={} transition_lookup_ns={} transition_apply_ns={} transition_apply_intersect_ns={} transition_apply_gss_ns={} token_accumulation_ns={} enqueue_merge_ns={} queue_lookup_ns={} queue_merge_ns={} queue_insert_ns={} insert_without_merge_count={} fuse_ns={} finalize_ns={} finalize_zero_ns={} finalize_dense_to_buf_ns={} finalize_cache_ns={} delta_prev_available={} delta_added_bits={} delta_removed_bits={} delta_unchanged_words={} delta_unchanged_bits={} delta_added_cost={} delta_removed_cost={} delta_copy_cost_words={} delta_scratch_estimated_cost={} delta_estimated_cost={} delta_estimated_savings={} delta_used_seed={} delta_added_word_group_hits={} delta_added_word_group_entries={} delta_removed_word_group_hits={} delta_removed_word_group_entries={} delta_added_byte_group_hits={} delta_added_byte_group_entries={} delta_removed_byte_group_hits={} delta_removed_byte_group_entries={} delta_added_token_iterations={} delta_added_token_entries={} delta_removed_token_iterations={} delta_removed_token_entries={} finalize_equal_dense_copy_seed={} finalize_delta_replay={} finalize_scratch_rebuild={} dense_words_visited={} dense_complement_path_used={} dense_normal_full_word_hits={} dense_normal_group_complement_hits={} dense_complement_full_word_hits={} dense_complement_full_byte_groups={} dense_complement_full_nibble_groups={} dense_complement_remaining_bits={} dense_normal_token_iterations={} dense_complement_token_iterations={} dense_normal_sparse_entries={} dense_normal_group_complement_sparse_entries={} dense_complement_sparse_entries={} dense_complement_heavy_dense_clears={} dense_complement_max_sparse_span={} dense_group_or_sparse_entries={} dense_group_andnot_sparse_entries={} dense_group_sparse_groups={} dense_group_sparse_total_entries={} dense_group_sparse_max_entries={} dense_group_dense_storage_words={} dense_raw_token_sparse_entries={} other_ns={} enqueue_calls={} merge_hits={} popped_items={} parser_dwa_transitions_enqueued={}",
8366                mask_queue_mode(),
8367                profile.total_ns,
8368                profile.seed_decompose_ns,
8369                profile.queue_pop_ns,
8370                loop_decompose_ns,
8371                profile.transition_lookup_ns,
8372                profile.transition_apply_ns,
8373                profile.transition_apply_intersect_ns,
8374                profile.transition_apply_gss_ns,
8375                profile.token_accumulation_ns,
8376                enqueue_exclusive_ns,
8377                queue_debug.lookup_total_ns,
8378                queue_debug.merge_total_ns,
8379                queue_debug.insert_total_ns,
8380                queue_debug.insert_without_merge_count,
8381                queue_debug.fuse_total_ns,
8382                profile.finalize_ns,
8383                profile.finalize_zero_ns,
8384                profile.finalize_dense_to_buf_ns,
8385                profile.finalize_cache_ns,
8386                profile.delta_prev_available,
8387                profile.delta_added_bits,
8388                profile.delta_removed_bits,
8389                profile.delta_unchanged_words,
8390                profile.delta_unchanged_bits,
8391                profile.delta_added_cost,
8392                profile.delta_removed_cost,
8393                profile.delta_copy_cost_words,
8394                profile.delta_scratch_estimated_cost,
8395                profile.delta_estimated_cost,
8396                profile.delta_estimated_savings,
8397                profile.delta_used_seed,
8398                profile.delta_replay.added_word_group_hits,
8399                profile.delta_replay.added_word_group_entries,
8400                profile.delta_replay.removed_word_group_hits,
8401                profile.delta_replay.removed_word_group_entries,
8402                profile.delta_replay.added_byte_group_hits,
8403                profile.delta_replay.added_byte_group_entries,
8404                profile.delta_replay.removed_byte_group_hits,
8405                profile.delta_replay.removed_byte_group_entries,
8406                profile.delta_replay.added_token_iterations,
8407                profile.delta_replay.added_token_entries,
8408                profile.delta_replay.removed_token_iterations,
8409                profile.delta_replay.removed_token_entries,
8410                profile.finalize_equal_dense_copy_seed,
8411                profile.finalize_delta_replay,
8412                profile.finalize_scratch_rebuild,
8413                profile.dense_to_buf.dense_words_visited,
8414                profile.dense_to_buf.complement_path_used,
8415                profile.dense_to_buf.normal_full_word_hits,
8416                profile.dense_to_buf.normal_group_complement_hits,
8417                profile.dense_to_buf.complement_full_word_hits,
8418                profile.dense_to_buf.complement_full_byte_groups,
8419                profile.dense_to_buf.complement_full_nibble_groups,
8420                profile.dense_to_buf.complement_remaining_bits,
8421                profile.dense_to_buf.normal_token_iterations,
8422                profile.dense_to_buf.complement_token_iterations,
8423                profile.dense_to_buf.normal_sparse_entries,
8424                profile.dense_to_buf.normal_group_complement_sparse_entries,
8425                profile.dense_to_buf.complement_sparse_entries,
8426                profile.dense_to_buf.complement_heavy_dense_clears,
8427                profile.dense_to_buf.complement_max_sparse_span,
8428                profile.dense_to_buf.group_or_sparse_entries,
8429                profile.dense_to_buf.group_andnot_sparse_entries,
8430                self.constraint.word_group_sparse_masks.len(),
8431                self.constraint.word_group_sparse_total_entries,
8432                self.constraint.word_group_sparse_max_entries,
8433                self.constraint.word_group_sparse_masks.len() * self.constraint.body_mask_len(),
8434                self.constraint.internal_token_buf_flat_len(),
8435                other_ns,
8436                queue_debug.enqueue_calls,
8437                queue_debug.merge_hit_count,
8438                queue_debug.popped_items,
8439                queue_debug.parser_dwa_transitions_enqueued,
8440            );
8441            emit_mask_inner_profile_line(&line);
8442        }
8443
8444        let returned_profile = profile.map(|profile| {
8445            let mut out = MaskProfile::from_parts(profile, *queue_debug, false, false);
8446            if out.total_ns == 0
8447                && let Some(start) = total_start {
8448                    out.total_ns = elapsed_ns(start);
8449                }
8450            out
8451        });
8452        scratch.merged_dense = merged;
8453        scratch.chain_merged_dense.clear();
8454
8455        returned_profile
8456    }
8457
8458    /// Packed u32 words: token i is bit i % 32 of word i / 32.
8459    pub fn mask(&self) -> Vec<u32> {
8460        let mut buf = vec![0u32; self.constraint.mask_bit_len().div_ceil(32)];
8461        self.fill_mask(&mut buf);
8462        buf
8463    }
8464
8465    // Fill `buf` with the allowed-token mask.
8466    //
8467    // `buf` must contain at least `constraint.mask_bit_len().div_ceil(32)` words. Any extra
8468    // words are cleared.
8469    fn static_mask_for_reset_branch(&self, gss: &ParserGSS, buf: &mut [u32]) {
8470        let reset_state = self.constraint.runtime_commit_initial_state();
8471        let mut shadow = self.clone();
8472        shadow.state.clear();
8473        shadow.state.insert_flat_alternative(reset_state, gss.clone());
8474        if let Some(factored) = shadow.lookahead_factored_mask_shadow() {
8475            factored.fill_mask_uncached(buf);
8476        } else {
8477            shadow.fill_mask_uncached(buf);
8478        }
8479        shadow.update_control_special_token_mask(buf);
8480    }
8481
8482    fn add_admissible_scoped_ignore_tokens(&self, buf: &mut [u32]) {
8483        if self.constraint.static_dynamic_overlay.is_none()
8484            || crate::env::var_os("GLRMASK_EXPERIMENT_SCOPED_IGNORE_EXACT_OVERLAY").is_none()
8485        {
8486            return;
8487        }
8488        let reset_state = self.constraint.runtime_commit_initial_state();
8489        let use_fusions = crate::env::var_os("GLRMASK_EXPERIMENT_SCOPED_IGNORE_FUSIONS").is_some();
8490        let use_residual_possible_matches =
8491            crate::env::var_os("GLRMASK_EXPERIMENT_SCOPED_IGNORE_RESIDUAL_PM").is_some();
8492        let mut suffix_mask = use_fusions.then(|| vec![0u32; buf.len()]);
8493        let mut candidate_mask = use_fusions.then(|| vec![0u32; buf.len()]);
8494        for (&tokenizer_state, gss) in self.state.iter() {
8495            if use_residual_possible_matches
8496                && tokenizer_state != reset_state
8497                && gss.all_accs_satisfy(|blocked: &TerminalsDisallowed| blocked.is_empty())
8498            {
8499                for &terminal in self.constraint.parser_skip_terminals() {
8500                    if !super::commit::parser_may_advance_on(&self.constraint, gss, terminal) {
8501                        continue;
8502                    }
8503                    self.constraint.visit_possible_match_original_tokens(
8504                        tokenizer_state,
8505                        terminal,
8506                        |token| set_original_mask_bit(buf, token),
8507                    );
8508                }
8509            }
8510            if tokenizer_state != reset_state
8511                || !gss.all_accs_satisfy(|blocked: &TerminalsDisallowed| blocked.is_empty())
8512            {
8513                continue;
8514            }
8515            for (terminal, tokens) in &self.constraint.scoped_ignore_only_tokens {
8516                if !super::commit::parser_may_advance_on(&self.constraint, gss, *terminal) {
8517                    continue;
8518                }
8519                for &token in tokens.iter() {
8520                    set_original_mask_bit(buf, token);
8521                }
8522                if !use_fusions {
8523                    continue;
8524                }
8525                let Some((_, fusions)) = self
8526                    .constraint
8527                    .scoped_ignore_prefix_fusions
8528                    .iter()
8529                    .find(|(candidate, _)| candidate == terminal)
8530                else {
8531                    continue;
8532                };
8533                let suffix_mask = suffix_mask
8534                    .as_deref_mut()
8535                    .expect("fusion suffix mask was requested");
8536                suffix_mask.fill(0);
8537                // A completed Skip inside one model token resets the lexer but
8538                // leaves this exact parser GSS unchanged. Test the remaining
8539                // suffix against *that branch-local reset state*, never against
8540                // the global union mask: another residual tokenizer branch may
8541                // admit the same suffix token for unrelated reasons.
8542                self.static_mask_for_reset_branch(gss, suffix_mask);
8543                for &(fused, suffix) in fusions.iter() {
8544                    if original_mask_contains(suffix_mask, suffix) {
8545                        set_original_mask_bit(
8546                            candidate_mask
8547                                .as_deref_mut()
8548                                .expect("fusion candidate mask was requested"),
8549                            fused,
8550                        );
8551                    }
8552                }
8553            }
8554        }
8555        if let Some(candidate_mask) = candidate_mask.as_deref()
8556            && candidate_mask.iter().any(|&word| word != 0)
8557        {
8558            super::dynamic_mask::or_mask_dynamic_candidate_additions(self, buf, candidate_mask);
8559        }
8560    }
8561
8562    fn lookahead_factored_mask_shadow(&self) -> Option<Box<Self>> {
8563        if self.constraint.has_template_parser() { return None; }
8564        if self.constraint.static_dynamic_overlay.is_none()
8565            || crate::env::var_os("GLRMASK_EXPERIMENT_MASK_LOOKAHEAD_FACTOR").is_none()
8566        {
8567            return None;
8568        }
8569
8570        // Two factors are sufficient to expose the parent continuation for the
8571        // nested-subgrammar return shape. Keep the experiment configurable for
8572        // differential work, but do not accumulate every intermediate factor:
8573        // only the deepest certified subset can add anything the shallower
8574        // subset could add, while carrying at least the same lookahead guards.
8575        let max_factor_depth = crate::env::var("GLRMASK_EXPERIMENT_MASK_LOOKAHEAD_FACTOR_MAX_DEPTH")
8576            .ok()
8577            .and_then(|value| value.parse::<usize>().ok())
8578            .unwrap_or(2)
8579            .min(8);
8580        let mut additions = SmallVec::<[(u32, ParserGSS); 4]>::new();
8581        for (&tokenizer_state, gss) in self.state.iter() {
8582            let mut factor = gss.clone();
8583            let mut blocked = SmallVec::<[TerminalID; 8]>::new();
8584            let mut deepest = None::<ParserGSS>;
8585            let use_fast_factor = crate::env::var_os(
8586                "GLRMASK_EXPERIMENT_FAST_LOOKAHEAD_FACTOR",
8587            )
8588            .is_some();
8589            let mut chain_forced = None::<BitSet>;
8590            let mut final_after = None::<BitSet>;
8591            let mut fast_guard_representable = true;
8592            for _ in 0..max_factor_depth {
8593                if use_fast_factor
8594                    && let Some(overlay) = self.constraint.static_dynamic_overlay.as_ref()
8595                    && !overlay.non_parent_only_parser_states.is_empty()
8596                {
8597                    let Some(top) = factor.single_exclusive_top_value() else {
8598                        break;
8599                    };
8600                    if !overlay
8601                        .non_parent_only_parser_states
8602                        .get(top as usize)
8603                        .copied()
8604                        .unwrap_or(false)
8605                    {
8606                        break;
8607                    }
8608                }
8609                let next = if use_fast_factor {
8610                    let Some((next, forced, after)) =
8611                        lookahead_reduction_factor_row_subset(&self.constraint.table, &factor)
8612                    else {
8613                        break;
8614                    };
8615                    chain_forced = Some(match chain_forced.take() {
8616                        None => forced,
8617                        Some(existing) => {
8618                            let not_forced = existing.difference(&forced);
8619                            existing.difference(&not_forced)
8620                        }
8621                    });
8622                    final_after = Some(after);
8623                    next
8624                } else {
8625                    let Some((next, newly_blocked)) =
8626                        lookahead_reduction_factor(&self.constraint.table, &factor)
8627                    else {
8628                        break;
8629                    };
8630                    for terminal in newly_blocked {
8631                        if !blocked.contains(&terminal) {
8632                            blocked.push(terminal);
8633                        }
8634                    }
8635                    next
8636                };
8637                factor = next;
8638                deepest = Some(factor.clone());
8639            }
8640            let Some(deepest) = deepest else {
8641                continue;
8642            };
8643            if use_fast_factor {
8644                blocked.clear();
8645                let Some(chain_forced) = chain_forced.as_ref() else {
8646                    continue;
8647                };
8648                let Some(final_after) = final_after.as_ref() else {
8649                    continue;
8650                };
8651                for bit in final_after.difference(chain_forced).iter_ones() {
8652                    if bit >= self.constraint.parser_terminal_count() as usize {
8653                        fast_guard_representable = false;
8654                        break;
8655                    }
8656                    blocked.push(bit as TerminalID);
8657                }
8658                if !fast_guard_representable {
8659                    continue;
8660                }
8661            }
8662            let guarded = deepest.apply(|acc: &TerminalsDisallowed| {
8663                let mut guarded = acc.clone();
8664                for &terminal in &blocked {
8665                    guarded = guarded.with_insert(tokenizer_state, terminal);
8666                }
8667                guarded
8668            });
8669            additions.push((tokenizer_state, guarded));
8670        }
8671        if additions.is_empty() {
8672            return None;
8673        }
8674
8675        // A mask-only speculative view clones only the live Arc-backed parser paths.
8676        let mut shadow = Box::new(ConstraintState {
8677            markers: None,
8678            constraint: self.constraint.clone(),
8679            state: self.state.clone(),
8680            epoch: self.generation(),
8681            mask_cache: StateMaskCache::new(),
8682        });
8683        for (tokenizer_state, factored) in additions {
8684            shadow
8685                .state
8686                .insert_flat_alternative(tokenizer_state, factored);
8687        }
8688        Some(shadow)
8689    }
8690
8691    /// Like `mask()`, but writes the words into `bitmask`.
8692    ///
8693    /// # Panics
8694    ///
8695    /// Panics if `bitmask` has fewer than `mask_bit_len().div_ceil(32)` words.
8696    pub fn fill_mask(&self, bitmask: &mut [u32]) {
8697        assert!(bitmask.len() >= self.constraint.mask_bit_len().div_ceil(32), "mask buffer has fewer words than required by the mask bit length");
8698        if self.terminated() {
8699            bitmask.fill(0);
8700            return;
8701        }
8702        self.fill_body_mask(bitmask);
8703        // Also finalize cached and ordinary dynamic masks: internal body paths
8704        // may return before their composed-mask endpoint filter runs.
8705        self.enforce_empty_byte_token_domain(bitmask);
8706        if !self.constraint.end_tokens.is_empty() {
8707            let accepting = self.frontier_complete();
8708            for &id in self.constraint.end_tokens.iter() {
8709                let word = &mut bitmask[id as usize / 32];
8710                let bit = 1u32 << (id % 32);
8711                // End IDs are reserved generation controls, not byte pieces.
8712                if accepting { *word |= bit; } else { *word &= !bit; }
8713            }
8714        }
8715    }
8716
8717    /// The mask's length in bits (max token ID plus one).
8718    pub fn mask_bit_len(&self) -> usize {
8719        self.constraint.mask_bit_len()
8720    }
8721
8722    pub(crate) fn fill_body_mask(&self, buf: &mut [u32]) {
8723        let required = self.constraint.body_mask_len();
8724        assert!(buf.len() >= required, "mask buffer is smaller than constraint mask");
8725        let (mask, tail) = buf.split_at_mut(required);
8726        tail.fill(0);
8727        let overlay = self.constraint.static_dynamic_overlay.as_ref();
8728        let authoritative_segmented = overlay.is_some_and(|overlay| {
8729            overlay.segmented_mask_authoritative
8730                && (!overlay.segmented_parser_components.is_empty()
8731                    || overlay.segmented_static_baseline)
8732        });
8733        let authoritative_dynamic_direct = overlay.is_some_and(|overlay| {
8734            overlay.segmented_mask_authoritative
8735                && !overlay.segmented_parser_components.is_empty()
8736                && overlay.segmented_parser_components.iter().all(|component| {
8737                    component.boundary.as_ref().is_some_and(|shard| {
8738                        matches!(
8739                            shard.backend,
8740                            crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect
8741                        )
8742                    })
8743                })
8744        });
8745        let prepared_boundary_domain = crate::env::var_os("GLRMASK_DISABLE_BOUNDARY_VOCAB").is_none()
8746            && overlay.is_some_and(|overlay| overlay.segmented_parser_components.iter().any(|component| {
8747                component.boundary.as_ref().is_some_and(|shard| {
8748                    matches!(shard.backend, crate::runtime::SegmentedBoundaryShardBackend::DynamicDirect)
8749                        && shard.candidate_tokens.is_some()
8750                })
8751            }));
8752        if authoritative_dynamic_direct && !prepared_boundary_domain {
8753            // DynamicDirect already computes the complete exact composed
8754            // language. Do not first construct component A masks only to OR the
8755            // same full language over them again. This is explicitly dynamic
8756            // evaluation (e.g. a differential reference side), so it runs
8757            // with a strict-static permit; static-side fallbacks below must
8758            // never be wrapped.
8759            crate::compiler::boundary_transfer::permit_strict_static_dynamic(|| {
8760                self.fill_mask_dynamic(mask)
8761            });
8762            self.clear_late_grammar_placeholder_mask(mask);
8763            return;
8764        }
8765        if authoritative_segmented {
8766            // The ordinary generation cache is valid for the complete
8767            // composed mask too. Commit retains it only when the exact
8768            // scoped parser/lexer state (including exclusions) is unchanged.
8769            if self.try_fill_mask_from_cache(mask) {
8770                self.clear_late_grammar_placeholder_mask(mask);
8771                return;
8772            }
8773            let filled = if authoritative_dynamic_direct {
8774                crate::compiler::boundary_transfer::permit_strict_static_dynamic(|| {
8775                    self.try_fill_mask_segmented_single_paths(mask)
8776                })
8777            } else { self.try_fill_mask_segmented_single_paths(mask) };
8778            if filled {
8779                self.update_control_special_token_mask(mask);
8780                self.clear_late_grammar_placeholder_mask(mask);
8781                self.store_mask_cache_reuse_dense(mask);
8782                return;
8783            }
8784            // Segmented projection is the common authoritative A/B path. A
8785            // recursive exceptional GSS must stay in the same scoped provider
8786            // coordinate, so dynamic evaluation selects a scoped provider for
8787            // the same shared walker rather than the transitional outer
8788            // parser/tokenizer. This fallback is a
8789            // hidden dynamic mask on a claimed static path: trap loudly under
8790            // the strict-static flag instead of silently contributing exact
8791            // dynamic admissions.
8792            if authoritative_dynamic_direct {
8793                crate::compiler::boundary_transfer::permit_strict_static_dynamic(|| self.fill_mask_dynamic(mask));
8794            } else {
8795                crate::compiler::boundary_transfer::strict_static_trap_dynamic(
8796                    "authoritative_segmented_projection_decline",
8797                );
8798                self.fill_mask_dynamic(mask);
8799            }
8800            self.clear_late_grammar_placeholder_mask(mask);
8801            return;
8802        }
8803        if self.constraint.uses_dynamic_runtime() {
8804            // Diagnostic escape hatch used by dynamic-mask performance tests:
8805            // bypass both the state-local last-mask cache and the lower-level
8806            // dynamic memo so repeated calls expose recomputation cost.
8807            let disable_dynamic_mask_cache = !super::dynamic_mask::dynamic_mask_cache_enabled();
8808            let profile_dynamic_cache = crate::env::var("GLRMASK_PROFILE_DYNAMIC_STATE_CACHE_GENERATION")
8809                .ok()
8810                .and_then(|value| value.parse::<u64>().ok())
8811                == Some(self.generation());
8812            let local_started = profile_dynamic_cache.then(Instant::now);
8813            let local_hit = !disable_dynamic_mask_cache && self.try_fill_mask_from_cache(mask);
8814            let local_us = local_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1e6);
8815            if !local_hit {
8816                let dynamic_started = profile_dynamic_cache.then(Instant::now);
8817                self.fill_mask_dynamic(mask);
8818                let dynamic_us = dynamic_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1e6);
8819                let store_started = profile_dynamic_cache.then(Instant::now);
8820                if !disable_dynamic_mask_cache {
8821                    self.store_mask_cache_reuse_dense(mask);
8822                }
8823                let store_us = store_started.map_or(0.0, |started| started.elapsed().as_secs_f64() * 1e6);
8824                if profile_dynamic_cache {
8825                    eprintln!(
8826                        "[glrmask/profile][dynamic_state_cache] generation={} local_hit=false local_us={:.1} dynamic_us={:.1} store_us={:.1}",
8827                        self.generation(),
8828                        local_us,
8829                        dynamic_us,
8830                        store_us,
8831                    );
8832                }
8833            } else if profile_dynamic_cache {
8834                eprintln!(
8835                    "[glrmask/profile][dynamic_state_cache] generation={} local_hit=true local_us={:.1}",
8836                    self.generation(),
8837                    local_us,
8838                );
8839            }
8840            let clear_started = profile_dynamic_cache.then(Instant::now);
8841            self.clear_late_grammar_placeholder_mask(mask);
8842            if let Some(clear_started) = clear_started {
8843                eprintln!(
8844                    "[glrmask/profile][dynamic_state_cache] generation={} clear_us={:.1}",
8845                    self.generation(),
8846                    clear_started.elapsed().as_secs_f64() * 1e6,
8847                );
8848            }
8849            return;
8850        }
8851        if crate::env::var_os("GLRMASK_EXPERIMENT_SEGMENTED_PARSER_MASK").is_some()
8852            && self
8853                .constraint
8854                .static_dynamic_overlay
8855                .as_ref()
8856                .is_some_and(|overlay| !overlay.segmented_parser_components.is_empty())
8857            && self.try_fill_mask_segmented_single_paths(mask) {
8858                self.update_control_special_token_mask(mask);
8859                if crate::env::var_os("GLRMASK_VALIDATE_SEGMENTED_PARSER_MASK").is_some() {
8860                    let mut reference = vec![0u32; mask.len()];
8861                    self.fill_mask_uncached(&mut reference);
8862                    self.update_control_special_token_mask(&mut reference);
8863                    if reference != mask {
8864                        let reference_only = (0..mask.len() * 32)
8865                            .filter(|&token| {
8866                                let word = token / 32;
8867                                let bit = token % 32;
8868                                ((reference[word] >> bit) & 1) != 0
8869                                    && ((mask[word] >> bit) & 1) == 0
8870                            })
8871                            .take(32)
8872                            .collect::<Vec<_>>();
8873                        let segmented_only = (0..mask.len() * 32)
8874                            .filter(|&token| {
8875                                let word = token / 32;
8876                                let bit = token % 32;
8877                                ((reference[word] >> bit) & 1) == 0
8878                                    && ((mask[word] >> bit) & 1) != 0
8879                            })
8880                            .take(32)
8881                            .collect::<Vec<_>>();
8882                        panic!(
8883                            "segmented component parser mask differs from flattened reference; reference_only={reference_only:?} segmented_only={segmented_only:?}"
8884                        );
8885                    }
8886                }
8887                self.store_mask_cache_reuse_dense(mask);
8888                self.clear_late_grammar_placeholder_mask(mask);
8889                return;
8890            }
8891        let cache_hit = self.try_fill_mask_from_cache(mask);
8892        if !cache_hit {
8893            let factor_profile = crate::env::var_os("GLRMASK_PROFILE_LOOKAHEAD_FACTOR").is_some();
8894            let factor_started = factor_profile.then(Instant::now);
8895            if let Some(shadow) = self.lookahead_factored_mask_shadow() {
8896                let factor_ns = factor_started.map_or(0, elapsed_ns);
8897                let fill_started = factor_profile.then(Instant::now);
8898                shadow.fill_mask_uncached(mask);
8899                if !shadow.or_two_dwa_boundary_parser_mask(mask) {
8900                    mask.fill(0);
8901                }
8902                if let Some(fill_started) = fill_started {
8903                    eprintln!(
8904                        "[glrmask/profile][lookahead_factor] built_ns={} fill_ns={} original_branches={} shadow_branches={}",
8905                        factor_ns,
8906                        elapsed_ns(fill_started),
8907                        self.state.len(),
8908                        shadow.state.len(),
8909                    );
8910                }
8911                self.store_mask_cache_reuse_dense(mask);
8912            } else {
8913                if let Some(factor_started) = factor_started {
8914                    eprintln!(
8915                        "[glrmask/profile][lookahead_factor] built_none_ns={} branches={}",
8916                        elapsed_ns(factor_started),
8917                        self.state.len(),
8918                    );
8919                }
8920                self.fill_mask_uncached(mask);
8921                if !self.or_two_dwa_boundary_parser_mask(mask) {
8922                    mask.fill(0);
8923                }
8924            }
8925            self.update_control_special_token_mask(mask);
8926            // Template exact-token admissions are overlaid on the byte DWA.
8927            // Replace any pre-overlay cached mask before it can be reused.
8928            if self.constraint.parser_has_controls()
8929                || self.constraint.uses_compact_segmented_parser_runtime()
8930                || (self.constraint.has_template_parser() && !self.constraint.special_token_terminals.is_empty())
8931            {
8932                self.store_mask_cache_reuse_dense(mask);
8933            }
8934        }
8935        self.add_admissible_scoped_ignore_tokens(mask);
8936        if crate::env::var_os("GLRMASK_EXPERIMENT_STATIC_DYNAMIC_OVERLAY").is_some() {
8937            super::dynamic_mask::or_mask_dynamic_additions(self, mask);
8938        }
8939        self.clear_late_grammar_placeholder_mask(mask);
8940        assert_dynamic_mask_equivalence(self, mask);
8941    }
8942
8943    pub(crate) fn fill_mask_timed_ns(&self, buf: &mut [u32]) -> u64 {
8944        let start = Instant::now();
8945        self.fill_mask(buf);
8946        start.elapsed().as_nanos() as u64
8947    }
8948
8949    pub(crate) fn fill_mask_profiled(&self, buf: &mut [u32]) -> MaskProfile {
8950        if self.terminated() || !self.constraint.end_tokens.is_empty() {
8951            let started = Instant::now();
8952            self.fill_mask(buf);
8953            return MaskProfile { total_ns: elapsed_ns(started), ..MaskProfile::default() };
8954        }
8955        let required = self.constraint.body_mask_len();
8956        assert!(buf.len() >= required, "mask buffer is smaller than constraint mask");
8957        let (buf, tail) = buf.split_at_mut(required);
8958        tail.fill(0);
8959        let total_start = Instant::now();
8960        if self.try_fill_mask_from_cache(buf) {
8961            self.clear_late_grammar_placeholder_mask(buf);
8962            return MaskProfile {
8963                total_ns: elapsed_ns(total_start),
8964                cache_hit: 1,
8965                ..MaskProfile::default()
8966            };
8967        }
8968        if self
8969            .constraint
8970            .static_dynamic_overlay
8971            .as_ref()
8972            .is_some_and(|overlay| {
8973                overlay.segmented_mask_authoritative
8974                    && (!overlay.segmented_parser_components.is_empty()
8975                        || overlay.segmented_static_baseline)
8976            })
8977        {
8978            // The recursive provider-native mask has different profiling
8979            // phases from the historical flattened/static evaluator. Preserve
8980            // exact semantics first; detailed segmented profiling can be added
8981            // independently without routing a recursive state through the
8982            // transitional outer parser/tokenizer.
8983            self.fill_mask(buf);
8984            return MaskProfile {
8985                total_ns: elapsed_ns(total_start),
8986                ..MaskProfile::default()
8987            };
8988        }
8989        if self.constraint.uses_dynamic_runtime() {
8990            self.fill_mask_dynamic(buf);
8991            self.clear_late_grammar_placeholder_mask(buf);
8992            self.store_mask_cache_reuse_dense(buf);
8993            return MaskProfile {
8994                total_ns: elapsed_ns(total_start),
8995                ..MaskProfile::default()
8996            };
8997        }
8998
8999        let profile = self
9000            .fill_mask_uncached_maybe_profile(buf, true)
9001            .unwrap_or_else(|| MaskProfile {
9002                total_ns: elapsed_ns(total_start),
9003                ..MaskProfile::default()
9004            });
9005        self.update_control_special_token_mask(buf);
9006        self.clear_late_grammar_placeholder_mask(buf);
9007        if self.constraint.parser_has_controls()
9008            || self.constraint.uses_compact_segmented_parser_runtime()
9009            || (self.constraint.has_template_parser() && !self.constraint.special_token_terminals.is_empty())
9010        {
9011            self.store_mask_cache_reuse_dense(buf);
9012        }
9013        profile
9014    }
9015
9016}
9017
9018#[cfg(test)]
9019mod boundary_dag_exact_tests {
9020    //! Exactness tests for the cap-free GSS x boundary-DWA product evaluator.
9021    //!
9022    //! Each test builds an adversarial ambiguous GSS with >128 distinct paths
9023    //! over shared tails (which makes the old
9024    //! `for_each_stack_top_first_bounded(128, _)` evaluator decline) and
9025    //! compares the memoized DAG evaluator against a literal per-path
9026    //! reference walk written independently in test code.
9027
9028    use super::{BoundaryMask64DagEvaluator, BoundaryWeightDagEvaluator};
9029    use crate::compiler::glr::accumulator::TerminalsDisallowed;
9030    use crate::compiler::glr::labels::{DEFAULT_LABEL, encode_positive_label};
9031    use crate::compiler::glr::parser::ParserGSS;
9032    use crate::compiler::stages::parser_dwa::SmallBoundaryDwa;
9033
9034    /// 2^8 = 256 stacks sharing a common bottom tail. Level `i` offers
9035    /// values `{2*i, 2*i+1}`; the shared tail is `[900, 901, 902]`.
9036    /// Bottom-to-top order in each stack.
9037    fn adversarial_stacks() -> Vec<(Vec<u32>, TerminalsDisallowed)> {
9038        let mut stacks = Vec::new();
9039        for bits in 0..256u32 {
9040            let mut stack = vec![900, 901, 902];
9041            for level in 0..8u32 {
9042                let pick = if (bits >> level) & 1 == 0 {
9043                    2 * level
9044                } else {
9045                    2 * level + 1
9046                };
9047                stack.push(pick);
9048            }
9049            stacks.push((stack, TerminalsDisallowed::new()));
9050        }
9051        stacks
9052    }
9053
9054    fn adversarial_gss() -> ParserGSS {
9055        ParserGSS::from_stacks(&adversarial_stacks())
9056    }
9057
9058    /// Compact DWA exercising positive edges, DEFAULT fallback, prefix
9059    /// finals, and a dead end. Single TSID, 6 tokens.
9060    ///
9061    /// - state 0: final=[0,2]; +0 -> 1 (mask [0,1]); DEFAULT -> 2 (all).
9062    /// - state 1: final=[1]; +2 -> 2 (mask [1,3]); no DEFAULT.
9063    /// - state 2: final=[3]; no transitions.
9064    fn adversarial_compact_dwa() -> SmallBoundaryDwa {
9065        let mut weights = vec![[0u64; 16]; 8];
9066        weights[1] = [0b00111111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9067        weights[2] = [0b00000101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9068        weights[3] = [0b00000011, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9069        weights[4] = [0b00001010, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9070        weights[5] = [0b00000010, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9071        weights[6] = [0b00001000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
9072        SmallBoundaryDwa {
9073            states: vec![
9074                crate::compiler::stages::parser_dwa::SmallBoundaryDwaState {
9075                    transitions: vec![
9076                        (encode_positive_label(0), 1, 3),
9077                        (DEFAULT_LABEL, 2, 1),
9078                    ],
9079                    final_weight: 2,
9080                },
9081                crate::compiler::stages::parser_dwa::SmallBoundaryDwaState {
9082                    transitions: vec![(encode_positive_label(2), 2, 4)],
9083                    final_weight: 5,
9084                },
9085                crate::compiler::stages::parser_dwa::SmallBoundaryDwaState {
9086                    transitions: vec![],
9087                    final_weight: 6,
9088                },
9089            ],
9090            weights,
9091            tsid_count: 1,
9092            token_count: 6,
9093        }
9094    }
9095
9096    /// Literal per-path reference walk for the compact representation,
9097    /// mirroring `accepted_mask_for_stack` but written independently here.
9098    fn reference_mask_for_stack(
9099        dwa: &SmallBoundaryDwa,
9100        tsid: u32,
9101        top_first: &[u32],
9102    ) -> u64 {
9103        if tsid >= dwa.tsid_count as u32 {
9104            return 0;
9105        }
9106        let mut state_id = dwa.start_state();
9107        let mut path_mask = dwa.all_token_mask();
9108        let mut accepted = 0u64;
9109        let accumulate = |state_id: u32, path_mask: u64, accepted: &mut u64| {
9110            let Some(state) = dwa.states.get(state_id as usize) else {
9111                return;
9112            };
9113            if state.final_weight != 0 {
9114                *accepted |= path_mask & dwa.weight_mask(state.final_weight, tsid);
9115            }
9116        };
9117        accumulate(state_id, path_mask, &mut accepted);
9118        for &parser_state in top_first {
9119            let label = encode_positive_label(parser_state);
9120            let Some(state) = dwa.states.get(state_id as usize) else {
9121                break;
9122            };
9123            let edge = state
9124                .transitions
9125                .iter()
9126                .find(|(edge_label, _, _)| *edge_label == label)
9127                .or_else(|| {
9128                    state
9129                        .transitions
9130                        .iter()
9131                        .find(|(edge_label, _, _)| *edge_label == DEFAULT_LABEL)
9132                });
9133            let Some(&(_, target, weight)) = edge else {
9134                break;
9135            };
9136            path_mask &= dwa.weight_mask(weight, tsid);
9137            if path_mask == 0 {
9138                break;
9139            }
9140            state_id = target;
9141            accumulate(state_id, path_mask, &mut accepted);
9142        }
9143        accepted
9144    }
9145
9146    fn reference_union_all_paths(
9147        dwa: &SmallBoundaryDwa,
9148        tsid: u32,
9149        gss: &ParserGSS,
9150        top_live: &dyn Fn(Option<u32>) -> bool,
9151    ) -> (u64, usize) {
9152        let mut union = 0u64;
9153        let mut count = 0usize;
9154        let complete = gss.for_each_stack_top_first_bounded(100_000, |top_first, _| {
9155            let live = match top_first.first().copied() {
9156                Some(top) => top_live(Some(top)),
9157                None => top_live(None),
9158            };
9159            if !live {
9160                return;
9161            }
9162            count += 1;
9163            union |= reference_mask_for_stack(dwa, tsid, top_first);
9164        });
9165        assert!(complete, "reference enumeration must complete");
9166        (union, count)
9167    }
9168
9169    #[test]
9170    fn compact_dag_evaluator_matches_literal_paths_past_128() {
9171        let gss = adversarial_gss();
9172        assert!(!gss.is_single_path());
9173        assert_eq!(gss.path_count_at_most(129), 129);
9174        // The old bounded evaluator declines on this GSS.
9175        assert!(!gss.for_each_stack_top_first_bounded(128, |_, _| {}));
9176
9177        let dwa = adversarial_compact_dwa();
9178        let dag = gss.indexed_dag();
9179        let top_live = |_: Option<u32>| true;
9180        let (expected, path_count) = reference_union_all_paths(&dwa, 0, &gss, &top_live);
9181        assert_eq!(path_count, 256);
9182
9183        let mut evaluator = BoundaryMask64DagEvaluator::new(&dwa, 0, &dag);
9184        let groups = evaluator.eval_root(&top_live);
9185        let mut actual = 0u64;
9186        for (group, mask) in &groups {
9187            // Single accumulator for every path: one correlated group.
9188            assert!(
9189                evaluator.group_accumulator(*group).is_some(),
9190                "every group resolves to an accumulator"
9191            );
9192            actual |= *mask;
9193        }
9194        assert_eq!(actual, expected);
9195    }
9196
9197    #[test]
9198    fn compact_dag_evaluator_respects_top_filter_and_default() {
9199        let gss = adversarial_gss();
9200        let dwa = adversarial_compact_dwa();
9201        let dag = gss.indexed_dag();
9202        // Tops are the level-7 values 14/15 (every stack ends with one of
9203        // them). Filter out top 14: half the paths use the +14 positive edge
9204        // (none here — 14 hits DEFAULT) and half keep top 15.
9205        let top_live = |top: Option<u32>| top.is_none_or(|value| value != 14);
9206        let (expected, path_count) = reference_union_all_paths(&dwa, 0, &gss, &top_live);
9207        assert!(path_count < 256 && path_count > 0);
9208
9209        let mut evaluator = BoundaryMask64DagEvaluator::new(&dwa, 0, &dag);
9210        let groups = evaluator.eval_root(&top_live);
9211        let actual = groups.values().fold(0u64, |acc, mask| acc | *mask);
9212        assert_eq!(actual, expected);
9213    }
9214
9215    #[test]
9216    fn compact_dag_evaluator_keeps_per_path_acc_groups() {
9217        // Two accumulator classes over the same 256 stack shapes: the
9218        // evaluator must keep their acceptances in separate groups so the
9219        // caller can intersect each with its own eligibility set.
9220        let mut stacks = adversarial_stacks();
9221        for (index, (_, acc)) in stacks.iter_mut().enumerate() {
9222            if index % 2 == 0 {
9223                *acc = acc.clone().with_insert(7, 9);
9224            }
9225        }
9226        let gss = ParserGSS::from_stacks(&stacks);
9227        assert!(!gss.is_single_path());
9228        let dwa = adversarial_compact_dwa();
9229        let dag = gss.indexed_dag();
9230        let top_live = |_: Option<u32>| true;
9231
9232        let mut evaluator = BoundaryMask64DagEvaluator::new(&dwa, 0, &dag);
9233        let groups = evaluator.eval_root(&top_live);
9234        assert!(
9235            groups.len() >= 2,
9236            "distinct accumulators stay in distinct groups, got {}",
9237            groups.len()
9238        );
9239        // Union over groups still equals the literal per-path union (the u64
9240        // acceptance itself is accumulator-independent; correlation is
9241        // enforced by the caller's per-group eligibility intersection).
9242        let (expected, _) = reference_union_all_paths(&dwa, 0, &gss, &top_live);
9243        let actual = groups.values().fold(0u64, |acc, mask| acc | *mask);
9244        assert_eq!(actual, expected);
9245    }
9246
9247    #[test]
9248    fn weight_dag_evaluator_matches_literal_paths_past_128() {
9249        use std::collections::BTreeSet;
9250        let gss = adversarial_gss();
9251        let compact = adversarial_compact_dwa();
9252        let dwa = compact.to_generic_dwa();
9253        let dag = gss.indexed_dag();
9254        let top_live = |_: Option<u32>| true;
9255
9256        let mut evaluator = BoundaryWeightDagEvaluator::new(&dwa, &dag);
9257        let groups = evaluator.eval_root(&top_live);
9258        let mut actual = BTreeSet::new();
9259        for (group, weight) in &groups {
9260            assert!(
9261                evaluator.group_accumulator(*group).is_some(),
9262                "every group resolves to an accumulator"
9263            );
9264            let Some(tokens) = weight.token_set_for_tsid_ref(0) else {
9265                continue;
9266            };
9267            actual.extend(tokens.iter());
9268        }
9269
9270        // Literal reference: per-path Weight walk over the generic DWA.
9271        let mut ops = crate::ds::weight::ScopedWeightOpCache::default();
9272        let mut expected = BTreeSet::new();
9273        let complete = gss.for_each_stack_top_first_bounded(100_000, |top_first, _| {
9274            let mut state_id = dwa.start_state();
9275            let mut path_weight = crate::ds::weight::Weight::all();
9276            let mut accepted = crate::ds::weight::Weight::empty();
9277            let accumulate = |state_id: u32,
9278                                  path_weight: &crate::ds::weight::Weight,
9279                                  accepted: &mut crate::ds::weight::Weight,
9280                                  ops: &mut crate::ds::weight::ScopedWeightOpCache| {
9281                if let Some(final_weight) = dwa
9282                    .states()
9283                    .get(state_id as usize)
9284                    .and_then(|state| state.final_weight.as_ref())
9285                {
9286                    let contribution = ops.intersection(path_weight, final_weight);
9287                    if !contribution.is_empty() {
9288                        *accepted = ops.union(accepted, &contribution);
9289                    }
9290                }
9291            };
9292            accumulate(state_id, &path_weight, &mut accepted, &mut ops);
9293            for &parser_state in top_first {
9294                let label = encode_positive_label(parser_state);
9295                let Some(state) = dwa.states().get(state_id as usize) else {
9296                    break;
9297                };
9298                let Some((target, edge_weight)) = state
9299                    .transitions
9300                    .get(&label)
9301                    .or_else(|| state.transitions.get(&DEFAULT_LABEL))
9302                else {
9303                    break;
9304                };
9305                path_weight = ops.intersection(&path_weight, edge_weight);
9306                if path_weight.is_empty() {
9307                    break;
9308                }
9309                state_id = *target;
9310                accumulate(state_id, &path_weight, &mut accepted, &mut ops);
9311            }
9312            if let Some(tokens) = accepted.token_set_for_tsid_ref(0) {
9313                expected.extend(tokens.iter());
9314            }
9315        });
9316        assert!(complete, "reference enumeration must complete");
9317        assert_eq!(actual, expected);
9318    }
9319
9320    #[test]
9321    fn weight_dag_evaluator_empty_stack_filtering() {
9322        // A lone empty stack contributes exactly the empty-prefix final; the
9323        // top filter admitting/rejecting the empty stack toggles the group.
9324        let stacks = vec![(Vec::new(), TerminalsDisallowed::new())];
9325        let gss = ParserGSS::from_stacks(&stacks);
9326        let compact = adversarial_compact_dwa();
9327        let dwa = compact.to_generic_dwa();
9328        let dag = gss.indexed_dag();
9329
9330        let accept_all = |_: Option<u32>| true;
9331        let mut evaluator = BoundaryWeightDagEvaluator::new(&dwa, &dag);
9332        let with_empty = evaluator.eval_root(&accept_all);
9333        assert_eq!(with_empty.len(), 1);
9334        let group_weight = with_empty.values().next().expect("one group");
9335        let tokens: Vec<u32> = group_weight
9336            .token_set_for_tsid_ref(0)
9337            .map(|set| set.iter().collect())
9338            .unwrap_or_default();
9339        // Empty-prefix final of state 0 is weights[2] = {0, 2}.
9340        assert_eq!(tokens, vec![0, 2]);
9341
9342        let reject_empty = |top: Option<u32>| top.is_some();
9343        let mut evaluator = BoundaryWeightDagEvaluator::new(&dwa, &dag);
9344        let without_empty = evaluator.eval_root(&reject_empty);
9345        assert!(
9346            without_empty.is_empty(),
9347            "rejecting the empty stack drops its group"
9348        );
9349    }
9350
9351    #[test]
9352    fn shared_queue_boundary_providers_match_dag_oracles_with_correlated_groups() {
9353        let mut stacks = adversarial_stacks();
9354        for (index, (_, acc)) in stacks.iter_mut().enumerate() {
9355            if index % 2 == 0 { *acc = acc.clone().with_insert(7,9); }
9356        }
9357        stacks.push((Vec::new(), TerminalsDisallowed::new()));
9358        let compact = adversarial_compact_dwa();
9359        let generic = compact.to_generic_dwa();
9360        for gss in [ParserGSS::from_stacks(&stacks), ParserGSS::empty()] {
9361            for filter in 0..3 {
9362                let top_live = |top: Option<u32>| match filter {
9363                    0 => true,
9364                    1 => top.is_some_and(|value| value != 14),
9365                    _ => false,
9366                };
9367                for (language, accumulator) in gss.partition_by_accumulator() {
9368                    let original = language.apply(|_| accumulator.clone());
9369                    let dag = original.indexed_dag();
9370                    let mut oracle = BoundaryMask64DagEvaluator::new(&compact,0,&dag);
9371                    let expected = oracle.eval_root(&top_live).values().fold(0,|a,b|a|b);
9372                    let compact_actual = super::boundary_mask64_via_shared_queue(&compact,0,&language,&top_live)
9373                        .map_or(0,|a|a.0.iter().fold(0,|bits,(_,w)|bits|w[0]));
9374                    let generic_actual = super::boundary_weight_mask_via_shared_queue(
9375                        &generic,&[0],compact.token_count as usize,&language,&top_live,
9376                    ).map_or(0,|a|a.0.iter().fold(0,|bits,(_,w)|bits|w[0]));
9377                    assert_eq!(compact_actual,expected,"compact group={accumulator:?} filter={filter}");
9378                    assert_eq!(generic_actual,expected,"generic group={accumulator:?} filter={filter}");
9379                }
9380            }
9381        }
9382    }
9383
9384    #[test]
9385    fn shared_boundary_queue_keeps_tokenizer_coordinates_separate() {
9386        let mut compact = adversarial_compact_dwa();
9387        compact.tsid_count = 2;
9388        for (index, weight) in compact.weights.iter_mut().enumerate() {
9389            // Distinct per-coordinate languages, including a transition which
9390            // is dead only in coordinate 1. Merging coordinates would admit
9391            // tokens that the independent per-coordinate oracle rejects.
9392            weight[1] = if index == 3 {
9393                0
9394            } else {
9395                ((weight[0] << 1) | (weight[0] >> 5)) & 0b11_1111
9396            };
9397        }
9398        let generic = compact.to_generic_dwa();
9399        let mut stacks = adversarial_stacks();
9400        stacks.push((Vec::new(), TerminalsDisallowed::new()));
9401        for (index, (_, accumulator)) in stacks.iter_mut().enumerate() {
9402            if index % 3 == 0 {
9403                *accumulator = accumulator.clone().with_insert(7, 9);
9404            }
9405        }
9406        let gss = ParserGSS::from_stacks(&stacks);
9407        for filter in 0..3 {
9408            let top_live = |top: Option<u32>| match filter {
9409                0 => true,
9410                1 => top.is_some_and(|value| value != 14),
9411                _ => false,
9412            };
9413            for (language, accumulator) in gss.partition_by_accumulator() {
9414                let original = language.apply(|_| accumulator.clone());
9415                let dag = original.indexed_dag();
9416                for coordinates in [&[0, 1][..], &[1][..]] {
9417                    let actual = super::boundary_weight_mask_via_shared_queue(
9418                        &generic,
9419                        coordinates,
9420                        compact.token_count as usize,
9421                        &language,
9422                        &top_live,
9423                    );
9424                    for tsid in 0..2 {
9425                        let expected = if coordinates.contains(&tsid) {
9426                            let mut oracle = BoundaryMask64DagEvaluator::new(
9427                                &compact, tsid, &dag,
9428                            );
9429                            oracle.eval_root(&top_live).values().fold(0, |a, b| a | b)
9430                        } else {
9431                            0
9432                        };
9433                        let observed = actual.as_ref().map_or(0, |allowed| {
9434                            allowed.0.iter()
9435                                .filter(|(coordinate, _)| *coordinate == tsid)
9436                                .fold(0, |bits, (_, words)| bits | words[0])
9437                        });
9438                        assert_eq!(observed, expected,
9439                            "coordinate={tsid} selected={coordinates:?} group={accumulator:?} filter={filter}");
9440                    }
9441                }
9442            }
9443        }
9444    }
9445}
9446
9447/// Clear a sorted, unique empty-spelling inventory outside the live exact
9448/// intervals. Allowed spans are skipped by binary search, including overlaps;
9449/// this never introduces a bit that the body mask did not already contain.
9450fn retain_live_empty_byte_ranges(
9451    mask: &mut [u32],
9452    empty_ids: &[u32],
9453    live_ranges: &mut [(u32, u32)],
9454) {
9455    fn clear_ids(mask: &mut [u32], ids: &[u32]) {
9456        let Some((&start, &end)) = ids.first().zip(ids.last()) else { return; };
9457        // Sorted unique IDs with this cardinality constitute a complete span.
9458        // Clear dense uncovered spans wordwise rather than once per model ID.
9459        if u64::from(end) - u64::from(start) + 1 == ids.len() as u64 {
9460            let first = start as usize / 32;
9461            if first >= mask.len() { return; }
9462            let last = (end as usize / 32).min(mask.len() - 1);
9463            let first_bits = u32::MAX << (start % 32);
9464            let last_bits = if last == end as usize / 32 {
9465                u32::MAX >> (31 - end % 32)
9466            } else { u32::MAX };
9467            if first == last {
9468                mask[first] &= !(first_bits & last_bits);
9469            } else {
9470                mask[first] &= !first_bits;
9471                mask[first + 1..last].fill(0);
9472                mask[last] &= !last_bits;
9473            }
9474        } else {
9475            for &id in ids {
9476                if let Some(word) = mask.get_mut(id as usize / 32) {
9477                    *word &= !(1u32 << (id % 32));
9478                }
9479            }
9480        }
9481    }
9482    live_ranges.sort_unstable();
9483    let mut remaining = empty_ids;
9484    for &(start, end) in live_ranges.iter() {
9485        let before = remaining.partition_point(|&id| id < start);
9486        clear_ids(mask, &remaining[..before]);
9487        remaining = &remaining[before..];
9488        let through = remaining.partition_point(|&id| id <= end);
9489        remaining = &remaining[through..];
9490        if remaining.is_empty() { return; }
9491    }
9492    clear_ids(mask, remaining);
9493}
9494
9495#[cfg(test)]
9496mod empty_byte_range_filter_tests {
9497    use super::retain_live_empty_byte_ranges;
9498
9499    #[test]
9500    fn interval_filter_matches_independent_pointwise_policy() {
9501        let domains = [
9502            (0..128).collect::<Vec<u32>>(),
9503            (0..128).filter(|id| id % 3 == 0).collect(),
9504            (17..96).collect(),
9505            vec![0, 31, 32, 63, 64, 95, 127, u32::MAX],
9506        ];
9507        let selections = [vec![], vec![(0, 127)], vec![(31, 63)],
9508            vec![(90, 127), (0, 32), (31, 96)],
9509            vec![(u32::MAX - 1, u32::MAX)], vec![(60, 95), (0, 1)]];
9510        for empty in &domains {
9511            for ranges in &selections {
9512                for words in [0, 1, 4] {
9513                    for seed in [0, u32::MAX, 0xa5a5_5a5a] {
9514                        let mut actual = vec![seed; words];
9515                        let mut expected = actual.clone();
9516                        for &id in empty {
9517                            if !ranges.iter().any(|&(start, end)| start <= id && id <= end)
9518                                && let Some(word) = expected.get_mut(id as usize / 32) {
9519                                    *word &= !(1u32 << (id % 32));
9520                                }
9521                        }
9522                        retain_live_empty_byte_ranges(&mut actual, empty, &mut ranges.clone());
9523                        assert_eq!(actual, expected, "domain={empty:?}, ranges={ranges:?}");
9524                    }
9525                }
9526            }
9527        }
9528    }
9529
9530    #[test]
9531    fn full_and_nearly_full_128k_empty_domains_skip_allowed_spans() {
9532        let ids = (0..131_072).collect::<Vec<u32>>();
9533        let mut mask = vec![u32::MAX; 4096];
9534        retain_live_empty_byte_ranges(&mut mask, &ids, &mut [(0, 131_071)]);
9535        assert!(mask.iter().all(|&word| word == u32::MAX));
9536        retain_live_empty_byte_ranges(&mut mask, &ids, &mut [(65_537, 131_071), (0, 65_535)]);
9537        assert_eq!(mask.iter().map(|word| word.count_ones()).sum::<u32>(), 131_071);
9538        assert_eq!(mask[65_536 / 32] & 1, 0);
9539    }
9540}